From 59e3465b6b9fa3767f9a344dce32716038eebc65 Mon Sep 17 00:00:00 2001 From: Ben Doherty Date: Mon, 13 Jan 2020 15:00:27 -0800 Subject: [PATCH] Update Assimp to 5.0.1 (#2027) --- third_party/libassimp/.editorconfig | 22 + third_party/libassimp/.gitignore | 77 + third_party/libassimp/.travis.yml | 19 - .../libassimp/BUILDBINARIES_EXAMPLE.bat | 26 + third_party/libassimp/Build.md | 43 +- third_party/libassimp/CMakeLists.txt | 286 +- third_party/libassimp/INSTALL | 11 +- third_party/libassimp/Readme.md | 19 +- third_party/libassimp/appveyor.yml | 67 - third_party/libassimp/assimp.pc.in | 2 +- .../libassimp/assimpTargets-debug.cmake.in | 104 +- .../libassimp/assimpTargets-release.cmake.in | 107 +- third_party/libassimp/assimpTargets.cmake.in | 6 +- third_party/libassimp/cmake/HunterGate.cmake | 540 ++ .../cmake/assimp-hunter-config.cmake.in | 14 + .../libassimp/code/{ => 3DS}/3DSConverter.cpp | 4 +- .../libassimp/code/{ => 3DS}/3DSExporter.cpp | 12 +- .../libassimp/code/{ => 3DS}/3DSExporter.h | 2 +- .../libassimp/code/{ => 3DS}/3DSHelper.h | 2 +- .../libassimp/code/{ => 3DS}/3DSLoader.cpp | 18 +- .../libassimp/code/{ => 3DS}/3DSLoader.h | 2 +- .../libassimp/code/{ => 3MF}/3MFXmlTags.h | 2 +- .../libassimp/code/{ => 3MF}/D3MFExporter.cpp | 8 +- .../libassimp/code/{ => 3MF}/D3MFExporter.h | 2 +- .../libassimp/code/{ => 3MF}/D3MFImporter.cpp | 6 +- .../libassimp/code/{ => 3MF}/D3MFImporter.h | 2 +- .../libassimp/code/3MF/D3MFOpcPackage.cpp | 207 + .../libassimp/code/{ => 3MF}/D3MFOpcPackage.h | 9 +- .../libassimp/code/{ => AC}/ACLoader.cpp | 4 +- .../libassimp/code/{ => AC}/ACLoader.h | 2 +- .../libassimp/code/{ => AMF}/AMFImporter.cpp | 4 +- .../libassimp/code/{ => AMF}/AMFImporter.hpp | 2 +- .../code/{ => AMF}/AMFImporter_Geometry.cpp | 2 +- .../code/{ => AMF}/AMFImporter_Macro.hpp | 2 +- .../code/{ => AMF}/AMFImporter_Material.cpp | 2 +- .../code/{ => AMF}/AMFImporter_Node.hpp | 2 +- .../{ => AMF}/AMFImporter_Postprocess.cpp | 28 +- .../libassimp/code/{ => ASE}/ASELoader.cpp | 34 +- .../libassimp/code/{ => ASE}/ASELoader.h | 3 +- .../libassimp/code/{ => ASE}/ASEParser.cpp | 7 +- .../libassimp/code/{ => ASE}/ASEParser.h | 14 +- .../code/{ => Assbin}/AssbinExporter.cpp | 12 +- .../code/{ => Assbin}/AssbinExporter.h | 2 +- .../code/{ => Assbin}/AssbinLoader.cpp | 10 +- .../code/{ => Assbin}/AssbinLoader.h | 2 +- third_party/libassimp/code/Assjson/cencode.c | 109 + third_party/libassimp/code/Assjson/cencode.h | 31 + .../libassimp/code/Assjson/json_exporter.cpp | 809 ++ .../libassimp/code/Assjson/mesh_splitter.cpp | 320 + .../libassimp/code/Assjson/mesh_splitter.h | 61 + .../code/{ => Assxml}/AssxmlExporter.cpp | 19 +- .../code/{ => Assxml}/AssxmlExporter.h | 2 +- .../libassimp/code/{ => B3D}/B3DImporter.cpp | 12 +- .../libassimp/code/{ => B3D}/B3DImporter.h | 2 +- .../libassimp/code/{ => BVH}/BVHLoader.cpp | 2 +- .../libassimp/code/{ => BVH}/BVHLoader.h | 2 +- .../code/{ => Blender}/BlenderBMesh.cpp | 0 .../code/{ => Blender}/BlenderBMesh.h | 0 .../code/{ => Blender}/BlenderCustomData.cpp | 6 +- .../code/{ => Blender}/BlenderCustomData.h | 0 .../code/{ => Blender}/BlenderDNA.cpp | 2 +- .../libassimp/code/{ => Blender}/BlenderDNA.h | 4 +- .../code/{ => Blender}/BlenderDNA.inl | 2 +- .../code/{ => Blender}/BlenderIntermediate.h | 2 +- .../code/{ => Blender}/BlenderLoader.cpp | 29 +- .../code/{ => Blender}/BlenderLoader.h | 2 +- .../code/{ => Blender}/BlenderModifier.cpp | 2 +- .../code/{ => Blender}/BlenderModifier.h | 2 +- .../code/{ => Blender}/BlenderScene.cpp | 5 +- .../code/{ => Blender}/BlenderScene.h | 6 +- .../code/{ => Blender}/BlenderSceneGen.h | 0 .../code/{ => Blender}/BlenderTessellator.cpp | 2 +- .../code/{ => Blender}/BlenderTessellator.h | 8 +- .../libassimp/code/{ => C4D}/C4DImporter.cpp | 155 +- .../libassimp/code/{ => C4D}/C4DImporter.h | 18 +- .../code/{ => CApi}/AssimpCExport.cpp | 5 +- .../code/{ => CApi}/CInterfaceIOWrapper.cpp | 2 +- .../code/{ => CApi}/CInterfaceIOWrapper.h | 2 +- third_party/libassimp/code/CMakeLists.txt | 1237 +-- .../libassimp/code/{ => COB}/COBLoader.cpp | 31 +- .../libassimp/code/{ => COB}/COBLoader.h | 2 +- .../libassimp/code/{ => COB}/COBScene.h | 2 +- .../libassimp/code/{ => CSM}/CSMLoader.cpp | 2 +- .../libassimp/code/{ => CSM}/CSMLoader.h | 2 +- .../code/{ => Collada}/ColladaExporter.cpp | 151 +- .../code/{ => Collada}/ColladaExporter.h | 5 +- .../code/{ => Collada}/ColladaHelper.h | 10 +- .../code/{ => Collada}/ColladaLoader.cpp | 1398 +-- .../code/{ => Collada}/ColladaLoader.h | 12 +- .../code/{ => Collada}/ColladaParser.cpp | 2538 +++--- .../code/{ => Collada}/ColladaParser.h | 24 +- .../libassimp/code/{ => Common}/Assimp.cpp | 4 +- .../code/{ => Common}/BaseImporter.cpp | 35 +- .../code/{ => Common}/BaseProcess.cpp | 4 +- .../libassimp/code/{ => Common}/BaseProcess.h | 2 +- .../libassimp/code/{ => Common}/Bitmap.cpp | 2 +- .../code/{ => Common}/CreateAnimMesh.cpp | 4 - .../code/{ => Common}/DefaultIOStream.cpp | 2 +- .../code/{ => Common}/DefaultIOSystem.cpp | 151 +- .../code/{ => Common}/DefaultLogger.cpp | 2 +- .../{ => Common}/DefaultProgressHandler.h | 2 +- .../libassimp/code/{ => Common}/Exporter.cpp | 69 +- .../code/{ => Common}/FileLogStream.h | 2 +- .../code/{ => Common}/FileSystemFilter.h | 0 third_party/libassimp/code/{ => Common}/IFF.h | 0 .../libassimp/code/{ => Common}/Importer.cpp | 23 +- .../libassimp/code/{ => Common}/Importer.h | 2 +- .../code/{ => Common}/ImporterRegistry.cpp | 102 +- .../libassimp/code/{ => Common}/PolyTools.h | 2 +- .../code/{ => Common}/PostStepRegistry.cpp | 71 +- .../code/{ => Common}/RemoveComments.cpp | 2 +- .../code/{ => Common}/SGSpatialSort.cpp | 2 +- .../code/{ => Common}/SceneCombiner.cpp | 37 +- .../code/{ => Common}/ScenePreprocessor.cpp | 2 +- .../code/{ => Common}/ScenePreprocessor.h | 2 +- .../code/{ => Common}/ScenePrivate.h | 2 +- .../code/{ => Common}/SkeletonMeshBuilder.cpp | 2 +- .../code/{ => Common}/SpatialSort.cpp | 2 +- .../{ => Common}/SplitByBoneCountProcess.cpp | 2 +- .../{ => Common}/SplitByBoneCountProcess.h | 2 +- .../code/{ => Common}/StandardShapes.cpp | 42 +- .../code/{ => Common}/StdOStreamLogStream.h | 2 +- .../code/{ => Common}/Subdivision.cpp | 9 +- .../code/{ => Common}/TargetAnimation.cpp | 2 +- .../code/{ => Common}/TargetAnimation.h | 2 +- .../libassimp/code/{ => Common}/Version.cpp | 10 +- .../{ => Common}/VertexTriangleAdjacency.cpp | 2 +- .../{ => Common}/VertexTriangleAdjacency.h | 2 +- .../code/{ => Common}/Win32DebugLogStream.h | 2 +- .../code/Common/ZipArchiveIOSystem.cpp | 539 ++ .../code/{ => Common}/assbin_chunks.h | 0 .../libassimp/code/{ => Common}/scene.cpp | 2 +- .../libassimp/code/{ => Common}/simd.cpp | 2 +- .../libassimp/code/{ => Common}/simd.h | 2 +- third_party/libassimp/code/D3MFOpcPackage.cpp | 531 -- .../libassimp/code/{ => DXF}/DXFHelper.h | 2 +- .../libassimp/code/{ => DXF}/DXFLoader.cpp | 12 +- .../libassimp/code/{ => DXF}/DXFLoader.h | 2 +- .../libassimp/code/{ => FBX}/FBXAnimation.cpp | 6 +- .../code/{ => FBX}/FBXBinaryTokenizer.cpp | 24 +- .../libassimp/code/{ => FBX}/FBXCommon.h | 6 +- .../code/{ => FBX}/FBXCompileConfig.h | 2 +- .../libassimp/code/FBX/FBXConverter.cpp | 3615 ++++++++ .../libassimp/code/{ => FBX}/FBXConverter.h | 53 +- .../libassimp/code/{ => FBX}/FBXDeformer.cpp | 49 +- .../libassimp/code/{ => FBX}/FBXDocument.cpp | 31 +- .../libassimp/code/{ => FBX}/FBXDocument.h | 163 +- .../code/{ => FBX}/FBXDocumentUtil.cpp | 2 +- .../code/{ => FBX}/FBXDocumentUtil.h | 14 +- .../code/{ => FBX}/FBXExportNode.cpp | 17 +- .../libassimp/code/{ => FBX}/FBXExportNode.h | 33 +- .../code/{ => FBX}/FBXExportProperty.cpp | 257 +- .../code/{ => FBX}/FBXExportProperty.h | 50 +- .../libassimp/code/{ => FBX}/FBXExporter.cpp | 287 +- .../libassimp/code/{ => FBX}/FBXExporter.h | 4 +- .../code/{ => FBX}/FBXImportSettings.h | 41 +- .../libassimp/code/{ => FBX}/FBXImporter.cpp | 28 +- .../libassimp/code/{ => FBX}/FBXImporter.h | 2 +- .../libassimp/code/{ => FBX}/FBXMaterial.cpp | 65 +- .../code/{ => FBX}/FBXMeshGeometry.cpp | 103 +- .../code/{ => FBX}/FBXMeshGeometry.h | 58 +- .../libassimp/code/{ => FBX}/FBXModel.cpp | 2 +- .../code/{ => FBX}/FBXNodeAttribute.cpp | 2 +- .../libassimp/code/{ => FBX}/FBXParser.cpp | 14 +- .../libassimp/code/{ => FBX}/FBXParser.h | 2 +- .../code/{ => FBX}/FBXProperties.cpp | 2 +- .../libassimp/code/{ => FBX}/FBXProperties.h | 2 +- .../libassimp/code/{ => FBX}/FBXTokenizer.cpp | 2 +- .../libassimp/code/{ => FBX}/FBXTokenizer.h | 14 +- third_party/libassimp/code/FBX/FBXUtil.cpp | 243 + .../libassimp/code/{ => FBX}/FBXUtil.h | 36 +- third_party/libassimp/code/FBXConverter.cpp | 3092 ------- third_party/libassimp/code/FBXUtil.cpp | 120 - .../libassimp/code/{ => HMP}/HMPFileData.h | 2 +- .../libassimp/code/{ => HMP}/HMPLoader.cpp | 10 +- .../libassimp/code/{ => HMP}/HMPLoader.h | 7 +- .../code/{ => HMP}/HalfLifeFileData.h | 2 +- .../code/Importer/IFC/IFCBoolean.cpp | 6 +- .../libassimp/code/Importer/IFC/IFCCurve.cpp | 9 +- .../code/Importer/IFC/IFCGeometry.cpp | 19 +- .../libassimp/code/Importer/IFC/IFCLoader.cpp | 53 +- .../libassimp/code/Importer/IFC/IFCLoader.h | 2 +- .../code/Importer/IFC/IFCMaterial.cpp | 2 +- .../code/Importer/IFC/IFCOpenings.cpp | 19 +- .../code/Importer/IFC/IFCProfile.cpp | 2 +- .../code/Importer/IFC/IFCReaderGen_2x3.h | 2 +- .../libassimp/code/Importer/IFC/IFCUtil.cpp | 15 +- .../libassimp/code/Importer/IFC/IFCUtil.h | 4 +- .../Importer/STEPParser/STEPFileEncoding.cpp | 8 +- .../Importer/STEPParser/STEPFileEncoding.h | 2 +- .../Importer/STEPParser/STEPFileReader.cpp | 102 +- .../code/Importer/STEPParser/STEPFileReader.h | 6 +- .../code/Importer/StepFile/StepFileGen1.cpp | 2 +- .../Importer/StepFile/StepFileImporter.cpp | 6 +- .../code/Importer/StepFile/StepFileImporter.h | 6 +- .../code/Importer/StepFile/StepReaderGen.h | 2 +- .../libassimp/code/{ => Irr}/IRRLoader.cpp | 79 +- .../libassimp/code/{ => Irr}/IRRLoader.h | 35 +- .../code/{ => Irr}/IRRMeshLoader.cpp | 2 +- .../libassimp/code/{ => Irr}/IRRMeshLoader.h | 2 +- .../libassimp/code/{ => Irr}/IRRShared.cpp | 2 +- .../libassimp/code/{ => Irr}/IRRShared.h | 0 .../libassimp/code/{ => LWO}/LWOAnimation.cpp | 2 +- .../libassimp/code/{ => LWO}/LWOAnimation.h | 2 +- .../libassimp/code/{ => LWO}/LWOBLoader.cpp | 2 +- .../libassimp/code/{ => LWO}/LWOFileData.h | 6 +- .../libassimp/code/{ => LWO}/LWOLoader.cpp | 12 +- .../libassimp/code/{ => LWO}/LWOLoader.h | 2 +- .../libassimp/code/{ => LWO}/LWOMaterial.cpp | 7 +- .../libassimp/code/{ => LWS}/LWSLoader.cpp | 11 +- .../libassimp/code/{ => LWS}/LWSLoader.h | 5 +- .../libassimp/code/{ => MD2}/MD2FileData.h | 2 +- .../libassimp/code/{ => MD2}/MD2Loader.cpp | 4 +- .../libassimp/code/{ => MD2}/MD2Loader.h | 2 +- .../libassimp/code/{ => MD2}/MD2NormalTable.h | 2 +- .../libassimp/code/{ => MD3}/MD3FileData.h | 12 +- .../libassimp/code/{ => MD3}/MD3Loader.cpp | 62 +- .../libassimp/code/{ => MD3}/MD3Loader.h | 2 +- .../libassimp/code/{ => MD4}/MD4FileData.h | 0 .../libassimp/code/{ => MD5}/MD5Loader.cpp | 23 +- .../libassimp/code/{ => MD5}/MD5Loader.h | 2 +- .../libassimp/code/{ => MD5}/MD5Parser.cpp | 11 +- .../libassimp/code/{ => MD5}/MD5Parser.h | 2 +- .../libassimp/code/{ => MDC}/MDCFileData.h | 2 +- .../libassimp/code/{ => MDC}/MDCLoader.cpp | 11 +- .../libassimp/code/{ => MDC}/MDCLoader.h | 2 +- .../libassimp/code/{ => MDC}/MDCNormalTable.h | 0 .../code/{ => MDL}/MDLDefaultColorMap.h | 2 +- .../libassimp/code/{ => MDL}/MDLFileData.h | 2 +- .../libassimp/code/{ => MDL}/MDLLoader.cpp | 50 +- .../libassimp/code/{ => MDL}/MDLLoader.h | 22 +- .../code/{ => MDL}/MDLMaterialLoader.cpp | 2 +- .../libassimp/code/{ => MMD}/MMDCpp14.h | 2 +- .../libassimp/code/{ => MMD}/MMDImporter.cpp | 12 +- .../libassimp/code/{ => MMD}/MMDImporter.h | 0 .../libassimp/code/{ => MMD}/MMDPmdParser.h | 2 +- .../libassimp/code/{ => MMD}/MMDPmxParser.cpp | 8 +- .../libassimp/code/{ => MMD}/MMDPmxParser.h | 2 +- .../libassimp/code/{ => MMD}/MMDVmdParser.h | 2 +- .../libassimp/code/{ => MS3D}/MS3DLoader.cpp | 2 +- .../libassimp/code/{ => MS3D}/MS3DLoader.h | 2 +- .../code/{ => Material}/MaterialSystem.cpp | 32 +- .../code/{ => Material}/MaterialSystem.h | 2 +- .../libassimp/code/{ => NDO}/NDOLoader.cpp | 2 +- .../libassimp/code/{ => NDO}/NDOLoader.h | 0 .../libassimp/code/{ => NFF}/NFFLoader.cpp | 2 +- .../libassimp/code/{ => NFF}/NFFLoader.h | 2 +- .../libassimp/code/{ => OFF}/OFFLoader.cpp | 2 +- .../libassimp/code/{ => OFF}/OFFLoader.h | 2 +- .../libassimp/code/{ => Obj}/ObjExporter.cpp | 6 +- .../libassimp/code/{ => Obj}/ObjExporter.h | 2 +- .../libassimp/code/{ => Obj}/ObjFileData.h | 5 +- .../code/{ => Obj}/ObjFileImporter.cpp | 80 +- .../code/{ => Obj}/ObjFileImporter.h | 2 +- .../code/{ => Obj}/ObjFileMtlImporter.cpp | 2 +- .../code/{ => Obj}/ObjFileMtlImporter.h | 2 +- .../code/{ => Obj}/ObjFileParser.cpp | 53 +- .../libassimp/code/{ => Obj}/ObjFileParser.h | 4 +- .../libassimp/code/{ => Obj}/ObjTools.h | 2 +- .../code/{ => Ogre}/OgreBinarySerializer.cpp | 4 +- .../code/{ => Ogre}/OgreBinarySerializer.h | 2 +- .../code/{ => Ogre}/OgreImporter.cpp | 2 +- .../libassimp/code/{ => Ogre}/OgreImporter.h | 2 +- .../code/{ => Ogre}/OgreMaterial.cpp | 2 +- .../code/{ => Ogre}/OgreParsingUtils.h | 2 +- .../libassimp/code/{ => Ogre}/OgreStructs.cpp | 2 +- .../libassimp/code/{ => Ogre}/OgreStructs.h | 2 +- .../code/{ => Ogre}/OgreXmlSerializer.cpp | 2 +- .../code/{ => Ogre}/OgreXmlSerializer.h | 2 +- .../code/{ => OpenGEX}/OpenGEXExporter.cpp | 2 +- .../code/{ => OpenGEX}/OpenGEXExporter.h | 2 +- .../code/{ => OpenGEX}/OpenGEXImporter.cpp | 19 +- .../code/{ => OpenGEX}/OpenGEXImporter.h | 2 +- .../code/{ => OpenGEX}/OpenGEXStructs.h | 2 +- .../libassimp/code/{ => Ply}/PlyExporter.cpp | 4 +- .../libassimp/code/{ => Ply}/PlyExporter.h | 2 +- .../libassimp/code/{ => Ply}/PlyLoader.cpp | 2 +- .../libassimp/code/{ => Ply}/PlyLoader.h | 2 +- .../libassimp/code/{ => Ply}/PlyParser.cpp | 2 +- .../libassimp/code/{ => Ply}/PlyParser.h | 2 +- .../CalcTangentsProcess.cpp | 8 +- .../CalcTangentsProcess.h | 6 +- .../ComputeUVMappingProcess.cpp | 8 +- .../ComputeUVMappingProcess.h | 5 +- .../ConvertToLHProcess.cpp | 68 +- .../{ => PostProcessing}/ConvertToLHProcess.h | 5 +- .../{ => PostProcessing}/DeboneProcess.cpp | 2 +- .../code/{ => PostProcessing}/DeboneProcess.h | 19 +- .../DropFaceNormalsProcess.cpp | 2 +- .../DropFaceNormalsProcess.h | 13 +- .../EmbedTexturesProcess.cpp | 18 +- .../EmbedTexturesProcess.h | 4 +- .../{ => PostProcessing}/FindDegenerates.cpp | 3 +- .../{ => PostProcessing}/FindDegenerates.h | 5 +- .../FindInstancesProcess.cpp | 34 +- .../FindInstancesProcess.h | 6 +- .../FindInvalidDataProcess.cpp | 120 +- .../FindInvalidDataProcess.h | 25 +- .../{ => PostProcessing}/FixNormalsStep.cpp | 2 +- .../{ => PostProcessing}/FixNormalsStep.h | 4 +- .../GenBoundingBoxesProcess.cpp | 115 + .../PostProcessing/GenBoundingBoxesProcess.h | 76 + .../GenFaceNormalsProcess.cpp | 2 +- .../GenFaceNormalsProcess.h | 4 +- .../GenVertexNormalsProcess.cpp | 2 +- .../GenVertexNormalsProcess.h | 20 +- .../ImproveCacheLocality.cpp | 71 +- .../ImproveCacheLocality.h | 9 +- .../JoinVerticesProcess.cpp | 27 +- .../JoinVerticesProcess.h | 12 +- .../LimitBoneWeightsProcess.cpp | 2 +- .../LimitBoneWeightsProcess.h | 36 +- .../MakeVerboseFormat.cpp | 31 +- .../{ => PostProcessing}/MakeVerboseFormat.h | 12 +- .../{ => PostProcessing}/OptimizeGraph.cpp | 4 +- .../code/{ => PostProcessing}/OptimizeGraph.h | 29 +- .../{ => PostProcessing}/OptimizeMeshes.cpp | 2 +- .../{ => PostProcessing}/OptimizeMeshes.h | 12 +- .../PretransformVertices.cpp | 2 +- .../PretransformVertices.h | 17 +- .../{ => PostProcessing}/ProcessHelper.cpp | 2 +- .../code/{ => PostProcessing}/ProcessHelper.h | 4 +- .../RemoveRedundantMaterials.cpp | 12 +- .../RemoveRedundantMaterials.h | 20 +- .../{ => PostProcessing}/RemoveVCProcess.cpp | 2 +- .../{ => PostProcessing}/RemoveVCProcess.h | 5 +- .../code/PostProcessing/ScaleProcess.cpp | 208 + .../code/{ => PostProcessing}/ScaleProcess.h | 17 +- .../SortByPTypeProcess.cpp | 57 +- .../{ => PostProcessing}/SortByPTypeProcess.h | 13 +- .../{ => PostProcessing}/SplitLargeMeshes.cpp | 2 +- .../{ => PostProcessing}/SplitLargeMeshes.h | 11 +- .../{ => PostProcessing}/TextureTransform.cpp | 2 +- .../{ => PostProcessing}/TextureTransform.h | 4 +- .../TriangulateProcess.cpp | 12 +- .../{ => PostProcessing}/TriangulateProcess.h | 10 +- .../ValidateDataStructure.cpp | 137 +- .../ValidateDataStructure.h | 5 +- .../code/{ => Q3BSP}/Q3BSPFileData.h | 2 +- .../code/{ => Q3BSP}/Q3BSPFileImporter.cpp | 21 +- .../code/{ => Q3BSP}/Q3BSPFileImporter.h | 14 +- .../code/{ => Q3BSP}/Q3BSPFileParser.cpp | 7 +- .../code/{ => Q3BSP}/Q3BSPFileParser.h | 15 +- .../libassimp/code/Q3BSPZipArchive.cpp | 315 - third_party/libassimp/code/Q3BSPZipArchive.h | 131 - .../libassimp/code/{ => Q3D}/Q3DLoader.cpp | 22 +- .../libassimp/code/{ => Q3D}/Q3DLoader.h | 2 +- .../libassimp/code/{ => Raw}/RawLoader.cpp | 2 +- .../libassimp/code/{ => Raw}/RawLoader.h | 2 +- .../libassimp/code/{ => SIB}/SIBImporter.cpp | 10 +- .../libassimp/code/{ => SIB}/SIBImporter.h | 2 +- .../libassimp/code/{ => SMD}/SMDLoader.cpp | 6 +- .../libassimp/code/{ => SMD}/SMDLoader.h | 2 +- .../libassimp/code/{ => STL}/STLExporter.cpp | 6 +- .../libassimp/code/{ => STL}/STLExporter.h | 2 +- .../libassimp/code/{ => STL}/STLLoader.cpp | 15 +- .../libassimp/code/{ => STL}/STLLoader.h | 2 +- .../libassimp/code/{ => Step}/STEPFile.h | 5 +- .../code/{ => Step}/StepExporter.cpp | 34 +- .../libassimp/code/{ => Step}/StepExporter.h | 2 +- .../code/{ => Terragen}/TerragenLoader.cpp | 2 +- .../code/{ => Terragen}/TerragenLoader.h | 2 +- .../code/{ => Unreal}/UnrealLoader.cpp | 8 +- .../code/{ => Unreal}/UnrealLoader.h | 5 +- .../libassimp/code/{ => X}/XFileExporter.cpp | 18 +- .../libassimp/code/{ => X}/XFileExporter.h | 2 +- .../libassimp/code/{ => X}/XFileHelper.h | 2 +- .../libassimp/code/{ => X}/XFileImporter.cpp | 16 +- .../libassimp/code/{ => X}/XFileImporter.h | 8 +- .../libassimp/code/{ => X}/XFileParser.cpp | 30 +- .../libassimp/code/{ => X}/XFileParser.h | 2 +- .../libassimp/code/{ => X3D}/FIReader.cpp | 8 +- .../libassimp/code/{ => X3D}/FIReader.hpp | 8 +- .../libassimp/code/{ => X3D}/X3DExporter.cpp | 2 +- .../libassimp/code/{ => X3D}/X3DExporter.hpp | 0 .../libassimp/code/{ => X3D}/X3DImporter.cpp | 70 +- .../libassimp/code/{ => X3D}/X3DImporter.hpp | 2 +- .../code/{ => X3D}/X3DImporter_Geometry2D.cpp | 8 +- .../code/{ => X3D}/X3DImporter_Geometry3D.cpp | 16 +- .../code/{ => X3D}/X3DImporter_Group.cpp | 2 +- .../code/{ => X3D}/X3DImporter_Light.cpp | 2 +- .../code/{ => X3D}/X3DImporter_Macro.hpp | 2 +- .../code/{ => X3D}/X3DImporter_Metadata.cpp | 2 +- .../code/{ => X3D}/X3DImporter_Networking.cpp | 4 +- .../code/{ => X3D}/X3DImporter_Node.hpp | 2 +- .../{ => X3D}/X3DImporter_Postprocess.cpp | 82 +- .../code/{ => X3D}/X3DImporter_Rendering.cpp | 14 +- .../code/{ => X3D}/X3DImporter_Shape.cpp | 2 +- .../code/{ => X3D}/X3DImporter_Texturing.cpp | 4 +- .../code/{ => X3D}/X3DVocabulary.cpp | 2 +- .../libassimp/code/{ => XGL}/XGLLoader.cpp | 18 +- .../libassimp/code/{ => XGL}/XGLLoader.h | 2 +- .../libassimp/code/{ => glTF}/glTFAsset.h | 75 +- .../libassimp/code/{ => glTF}/glTFAsset.inl | 232 +- .../code/{ => glTF}/glTFAssetWriter.h | 2 +- .../code/{ => glTF}/glTFAssetWriter.inl | 18 +- .../libassimp/code/glTF/glTFCommon.cpp | 193 + third_party/libassimp/code/glTF/glTFCommon.h | 248 + .../code/{ => glTF}/glTFExporter.cpp | 24 +- .../libassimp/code/{ => glTF}/glTFExporter.h | 2 +- .../code/{ => glTF}/glTFImporter.cpp | 104 +- .../libassimp/code/{ => glTF}/glTFImporter.h | 2 +- .../libassimp/code/{ => glTF2}/glTF2Asset.h | 118 +- .../libassimp/code/{ => glTF2}/glTF2Asset.inl | 278 +- .../code/{ => glTF2}/glTF2AssetWriter.h | 2 +- .../code/{ => glTF2}/glTF2AssetWriter.inl | 16 +- .../code/{ => glTF2}/glTF2Exporter.cpp | 44 +- .../code/{ => glTF2}/glTF2Exporter.h | 2 +- .../code/{ => glTF2}/glTF2Importer.cpp | 237 +- .../code/{ => glTF2}/glTF2Importer.h | 2 +- third_party/libassimp/code/makefile.mingw | 105 - third_party/libassimp/code/res/assimp.rc | 14 +- third_party/libassimp/code/res/resource.h | 4 +- .../libassimp/contrib/clipper/clipper.cpp | 10 +- .../libassimp/contrib/gtest/.gitignore | 2 - .../gtest/test/gtest-param-test_test.cc | 8 +- .../libassimp/contrib/irrXML/CMakeLists.txt | 9 +- .../libassimp/contrib/irrXML/CXMLReaderImpl.h | 13 +- .../libassimp/contrib/irrXML/irrString.h | 2 +- .../libassimp/contrib/irrXML/irrXML.cpp | 4 +- third_party/libassimp/contrib/irrXML/irrXML.h | 26 +- .../libassimp/contrib/poly2tri/AUTHORS | 2 +- .../libassimp/contrib/stb_image/stb_image.h | 7462 +++++++++++++++++ third_party/libassimp/contrib/zip/.gitignore | 38 - third_party/libassimp/contrib/zip/.travis.sh | 18 + third_party/libassimp/contrib/zip/.travis.yml | 18 +- .../libassimp/contrib/zip/CMakeLists.txt | 43 +- third_party/libassimp/contrib/zip/README.md | 340 +- .../libassimp/contrib/zip/appveyor.yml | 14 - .../libassimp/contrib/zip/cmake/asan-wrapper | 55 + .../zip/cmake/cmake_uninstall.cmake.in | 23 + third_party/libassimp/contrib/zip/src/miniz.h | 6010 ++++++++----- third_party/libassimp/contrib/zip/src/zip.c | 1252 +-- third_party/libassimp/contrib/zip/src/zip.h | 147 +- .../libassimp/contrib/zip/test/CMakeLists.txt | 12 + third_party/libassimp/contrib/zip/test/test.c | 472 +- .../libassimp/contrib/zip/test/test_miniz.c | 104 + .../libassimp/contrib/zlib/CMakeLists.txt | 9 +- .../contrib/dotzlib/DotZLib/ChecksumImpl.cs | 4 +- .../contrib/dotzlib/DotZLib/CircularBuffer.cs | 2 +- .../zlib/contrib/dotzlib/DotZLib/CodecBase.cs | 2 +- .../zlib/contrib/dotzlib/DotZLib/Deflater.cs | 2 +- .../zlib/contrib/dotzlib/DotZLib/DotZLib.cs | 2 +- .../contrib/dotzlib/DotZLib/GZipStream.cs | 2 +- .../zlib/contrib/dotzlib/DotZLib/Inflater.cs | 2 +- third_party/libassimp/doc/dox.h | 12 + .../libassimp/include/assimp/BaseImporter.h | 63 +- third_party/libassimp/include/assimp/Bitmap.h | 2 +- .../libassimp/include/assimp/BlobIOSystem.h | 2 +- .../libassimp/include/assimp/ByteSwapper.h | 2 +- .../libassimp/include/assimp/CreateAnimMesh.h | 2 +- .../include/assimp/DefaultIOStream.h | 2 +- .../include/assimp/DefaultIOSystem.h | 2 +- .../include/assimp/DefaultLogger.hpp | 2 +- .../libassimp/include/assimp/Exporter.hpp | 4 +- .../include/assimp/GenericProperty.h | 2 +- third_party/libassimp/include/assimp/Hash.h | 2 +- .../libassimp/include/assimp/IOStream.hpp | 2 +- .../libassimp/include/assimp/IOStreamBuffer.h | 7 +- .../libassimp/include/assimp/IOSystem.hpp | 2 +- .../libassimp/include/assimp/Importer.hpp | 2 +- .../libassimp/include/assimp/LineSplitter.h | 2 +- third_party/libassimp/include/assimp/LogAux.h | 2 +- .../libassimp/include/assimp/LogStream.hpp | 2 +- .../libassimp/include/assimp/Logger.hpp | 2 +- third_party/libassimp/include/assimp/Macros.h | 2 +- .../libassimp/include/assimp/MathFunctions.h | 29 +- .../include/assimp/MemoryIOWrapper.h | 113 +- .../libassimp/include/assimp/NullLogger.hpp | 2 +- .../libassimp/include/assimp/ParsingUtils.h | 5 +- .../libassimp/include/assimp/Profiler.h | 2 +- .../include/assimp/ProgressHandler.hpp | 2 +- .../libassimp/include/assimp/RemoveComments.h | 2 +- .../libassimp/include/assimp/SGSpatialSort.h | 2 +- .../libassimp/include/assimp/SceneCombiner.h | 4 +- .../include/assimp/SkeletonMeshBuilder.h | 2 +- .../include/assimp/SmoothingGroups.h | 2 +- .../libassimp/include/assimp/SpatialSort.h | 2 +- .../libassimp/include/assimp/StandardShapes.h | 2 +- .../libassimp/include/assimp/StreamReader.h | 9 +- .../libassimp/include/assimp/StreamWriter.h | 2 +- .../include/assimp/StringComparison.h | 2 +- .../libassimp/include/assimp/StringUtils.h | 2 +- .../libassimp/include/assimp/Subdivision.h | 2 +- .../libassimp/include/assimp/TinyFormatter.h | 2 +- third_party/libassimp/include/assimp/Vertex.h | 2 +- .../libassimp/include/assimp/XMLTools.h | 2 +- .../include/assimp/ZipArchiveIOSystem.h | 87 + .../assimp/aabb.h} | 85 +- .../libassimp/include/assimp/ai_assert.h | 9 +- third_party/libassimp/include/assimp/anim.h | 2 +- third_party/libassimp/include/assimp/camera.h | 9 +- .../libassimp/include/assimp/cfileio.h | 2 +- .../libassimp/include/assimp/cimport.h | 2 +- third_party/libassimp/include/assimp/color4.h | 2 +- .../libassimp/include/assimp/color4.inl | 6 +- third_party/libassimp/include/assimp/config.h | 47 +- .../libassimp/include/assimp/config.h.in | 47 +- third_party/libassimp/include/assimp/defs.h | 23 +- .../libassimp/include/assimp/importerdesc.h | 2 +- .../libassimp/include/assimp/irrXMLWrapper.h | 23 +- third_party/libassimp/include/assimp/light.h | 2 +- .../libassimp/include/assimp/material.h | 62 +- .../libassimp/include/assimp/material.inl | 2 +- .../libassimp/include/assimp/matrix3x3.h | 2 +- .../libassimp/include/assimp/matrix3x3.inl | 2 +- .../libassimp/include/assimp/matrix4x4.h | 2 +- .../libassimp/include/assimp/matrix4x4.inl | 11 +- third_party/libassimp/include/assimp/mesh.h | 32 +- .../libassimp/include/assimp/metadata.h | 2 +- .../libassimp/include/assimp/pbrmaterial.h | 2 +- .../libassimp/include/assimp/postprocess.h | 15 +- third_party/libassimp/include/assimp/qnan.h | 2 +- .../libassimp/include/assimp/quaternion.h | 2 +- .../libassimp/include/assimp/quaternion.inl | 2 +- third_party/libassimp/include/assimp/scene.h | 11 +- .../libassimp/include/assimp/texture.h | 6 +- third_party/libassimp/include/assimp/types.h | 32 +- .../libassimp/include/assimp/vector2.h | 2 +- .../libassimp/include/assimp/vector2.inl | 2 +- .../libassimp/include/assimp/vector3.h | 2 +- .../libassimp/include/assimp/vector3.inl | 2 +- .../libassimp/include/assimp/version.h | 2 +- .../packaging/windows-innosetup/script.iss | 103 - .../windows-innosetup/script_x64.iss | 74 + .../windows-innosetup/script_x86.iss | 75 + .../libassimp/port/AndroidJNI/README.md | 10 +- .../libassimp/port/AssimpNET/Readme.md | 2 +- third_party/libassimp/port/PyAssimp/README.md | 91 + .../libassimp/port/PyAssimp/pyassimp/core.py | 1096 ++- .../port/PyAssimp/pyassimp/formats.py | 2 +- .../port/PyAssimp/pyassimp/helper.py | 561 +- .../port/PyAssimp/pyassimp/postprocess.py | 1 + .../port/PyAssimp/pyassimp/structs.py | 4 +- .../port/PyAssimp/scripts/3d_viewer_py3.py | 38 +- .../scripts/fixed_pipeline_3d_viewer.py | 5 +- .../libassimp/port/PyAssimp/scripts/sample.py | 6 +- third_party/libassimp/port/PyAssimp/setup.py | 2 +- .../port/iOS/IPHONEOS_ARM64E_TOOLCHAIN.cmake | 17 + third_party/libassimp/port/iOS/build.sh | 2 +- .../jassimp/jassimp-native/src/jassimp.cpp | 28 +- .../port/jassimp/jassimp-native/src/jassimp.h | 2 +- .../jassimp/src/jassimp/AiAnimation.java | 46 +- .../jassimp/jassimp/src/jassimp/AiBone.java | 39 +- .../src/jassimp/AiClassLoaderIOSystem.java | 6 +- .../jassimp/jassimp/src/jassimp/AiColor.java | 22 +- .../jassimp/src/jassimp/AiMaterial.java | 87 +- .../jassimp/jassimp/src/jassimp/AiMesh.java | 178 +- .../jassimp/jassimp/src/jassimp/AiNode.java | 59 +- .../src/jassimp/AiProgressHandler.java | 46 + .../jassimp/src/jassimp/AiQuaternion.java | 25 +- .../jassimp/src/jassimp/AiSceneFlag.java | 16 +- .../jassimp/jassimp/src/jassimp/Jassimp.java | 104 +- third_party/libassimp/revision.h | 23 +- third_party/libassimp/revision.h.in | 21 + .../scripts/BlenderImporter/genblenddna.py | 4 +- .../scripts/StepImporter/CppGenerator.py | 18 +- .../scripts/StepImporter/ExpressReader.py | 3 +- .../StepImporter/StepReaderGen.cpp.template | 6 +- .../StepImporter/StepReaderGen.h.template | 37 +- third_party/libassimp/tnt/CMakeLists.txt | 276 +- third_party/libassimp/tnt/README.md | 9 +- 562 files changed, 29491 insertions(+), 14571 deletions(-) create mode 100644 third_party/libassimp/.editorconfig delete mode 100644 third_party/libassimp/.travis.yml create mode 100644 third_party/libassimp/BUILDBINARIES_EXAMPLE.bat delete mode 100644 third_party/libassimp/appveyor.yml create mode 100644 third_party/libassimp/cmake/HunterGate.cmake create mode 100644 third_party/libassimp/cmake/assimp-hunter-config.cmake.in rename third_party/libassimp/code/{ => 3DS}/3DSConverter.cpp (99%) rename third_party/libassimp/code/{ => 3DS}/3DSExporter.cpp (99%) rename third_party/libassimp/code/{ => 3DS}/3DSExporter.h (98%) rename third_party/libassimp/code/{ => 3DS}/3DSHelper.h (99%) rename third_party/libassimp/code/{ => 3DS}/3DSLoader.cpp (99%) rename third_party/libassimp/code/{ => 3DS}/3DSLoader.h (99%) rename third_party/libassimp/code/{ => 3MF}/3MFXmlTags.h (99%) rename third_party/libassimp/code/{ => 3MF}/D3MFExporter.cpp (98%) rename third_party/libassimp/code/{ => 3MF}/D3MFExporter.h (98%) rename third_party/libassimp/code/{ => 3MF}/D3MFImporter.cpp (99%) rename third_party/libassimp/code/{ => 3MF}/D3MFImporter.h (98%) create mode 100644 third_party/libassimp/code/3MF/D3MFOpcPackage.cpp rename third_party/libassimp/code/{ => 3MF}/D3MFOpcPackage.h (92%) rename third_party/libassimp/code/{ => AC}/ACLoader.cpp (99%) rename third_party/libassimp/code/{ => AC}/ACLoader.h (99%) rename third_party/libassimp/code/{ => AMF}/AMFImporter.cpp (99%) rename third_party/libassimp/code/{ => AMF}/AMFImporter.hpp (99%) rename third_party/libassimp/code/{ => AMF}/AMFImporter_Geometry.cpp (99%) rename third_party/libassimp/code/{ => AMF}/AMFImporter_Macro.hpp (99%) rename third_party/libassimp/code/{ => AMF}/AMFImporter_Material.cpp (99%) rename third_party/libassimp/code/{ => AMF}/AMFImporter_Node.hpp (99%) rename third_party/libassimp/code/{ => AMF}/AMFImporter_Postprocess.cpp (98%) rename third_party/libassimp/code/{ => ASE}/ASELoader.cpp (99%) rename third_party/libassimp/code/{ => ASE}/ASELoader.h (99%) rename third_party/libassimp/code/{ => ASE}/ASEParser.cpp (99%) rename third_party/libassimp/code/{ => ASE}/ASEParser.h (99%) rename third_party/libassimp/code/{ => Assbin}/AssbinExporter.cpp (99%) rename third_party/libassimp/code/{ => Assbin}/AssbinExporter.h (98%) rename third_party/libassimp/code/{ => Assbin}/AssbinLoader.cpp (99%) rename third_party/libassimp/code/{ => Assbin}/AssbinLoader.h (98%) create mode 100644 third_party/libassimp/code/Assjson/cencode.c create mode 100644 third_party/libassimp/code/Assjson/cencode.h create mode 100644 third_party/libassimp/code/Assjson/json_exporter.cpp create mode 100644 third_party/libassimp/code/Assjson/mesh_splitter.cpp create mode 100644 third_party/libassimp/code/Assjson/mesh_splitter.h rename third_party/libassimp/code/{ => Assxml}/AssxmlExporter.cpp (99%) rename third_party/libassimp/code/{ => Assxml}/AssxmlExporter.h (98%) rename third_party/libassimp/code/{ => B3D}/B3DImporter.cpp (99%) rename third_party/libassimp/code/{ => B3D}/B3DImporter.h (99%) rename third_party/libassimp/code/{ => BVH}/BVHLoader.cpp (99%) rename third_party/libassimp/code/{ => BVH}/BVHLoader.h (99%) rename third_party/libassimp/code/{ => Blender}/BlenderBMesh.cpp (100%) rename third_party/libassimp/code/{ => Blender}/BlenderBMesh.h (100%) rename third_party/libassimp/code/{ => Blender}/BlenderCustomData.cpp (95%) rename third_party/libassimp/code/{ => Blender}/BlenderCustomData.h (100%) rename third_party/libassimp/code/{ => Blender}/BlenderDNA.cpp (99%) rename third_party/libassimp/code/{ => Blender}/BlenderDNA.h (99%) rename third_party/libassimp/code/{ => Blender}/BlenderDNA.inl (99%) rename third_party/libassimp/code/{ => Blender}/BlenderIntermediate.h (99%) rename third_party/libassimp/code/{ => Blender}/BlenderLoader.cpp (97%) rename third_party/libassimp/code/{ => Blender}/BlenderLoader.h (99%) rename third_party/libassimp/code/{ => Blender}/BlenderModifier.cpp (99%) rename third_party/libassimp/code/{ => Blender}/BlenderModifier.h (99%) rename third_party/libassimp/code/{ => Blender}/BlenderScene.cpp (99%) rename third_party/libassimp/code/{ => Blender}/BlenderScene.h (99%) rename third_party/libassimp/code/{ => Blender}/BlenderSceneGen.h (100%) rename third_party/libassimp/code/{ => Blender}/BlenderTessellator.cpp (99%) rename third_party/libassimp/code/{ => Blender}/BlenderTessellator.h (97%) rename third_party/libassimp/code/{ => C4D}/C4DImporter.cpp (89%) rename third_party/libassimp/code/{ => C4D}/C4DImporter.h (97%) rename third_party/libassimp/code/{ => CApi}/AssimpCExport.cpp (98%) rename third_party/libassimp/code/{ => CApi}/CInterfaceIOWrapper.cpp (99%) rename third_party/libassimp/code/{ => CApi}/CInterfaceIOWrapper.h (98%) rename third_party/libassimp/code/{ => COB}/COBLoader.cpp (98%) rename third_party/libassimp/code/{ => COB}/COBLoader.h (99%) rename third_party/libassimp/code/{ => COB}/COBScene.h (99%) rename third_party/libassimp/code/{ => CSM}/CSMLoader.cpp (99%) rename third_party/libassimp/code/{ => CSM}/CSMLoader.h (98%) rename third_party/libassimp/code/{ => Collada}/ColladaExporter.cpp (94%) rename third_party/libassimp/code/{ => Collada}/ColladaExporter.h (99%) rename third_party/libassimp/code/{ => Collada}/ColladaHelper.h (98%) rename third_party/libassimp/code/{ => Collada}/ColladaLoader.cpp (58%) rename third_party/libassimp/code/{ => Collada}/ColladaLoader.h (97%) rename third_party/libassimp/code/{ => Collada}/ColladaParser.cpp (50%) rename third_party/libassimp/code/{ => Collada}/ColladaParser.h (94%) rename third_party/libassimp/code/{ => Common}/Assimp.cpp (99%) rename third_party/libassimp/code/{ => Common}/BaseImporter.cpp (95%) rename third_party/libassimp/code/{ => Common}/BaseProcess.cpp (97%) rename third_party/libassimp/code/{ => Common}/BaseProcess.h (99%) rename third_party/libassimp/code/{ => Common}/Bitmap.cpp (99%) rename third_party/libassimp/code/{ => Common}/CreateAnimMesh.cpp (96%) rename third_party/libassimp/code/{ => Common}/DefaultIOStream.cpp (99%) rename third_party/libassimp/code/{ => Common}/DefaultIOSystem.cpp (58%) rename third_party/libassimp/code/{ => Common}/DefaultLogger.cpp (99%) rename third_party/libassimp/code/{ => Common}/DefaultProgressHandler.h (98%) rename third_party/libassimp/code/{ => Common}/Exporter.cpp (94%) rename third_party/libassimp/code/{ => Common}/FileLogStream.h (98%) rename third_party/libassimp/code/{ => Common}/FileSystemFilter.h (100%) rename third_party/libassimp/code/{ => Common}/IFF.h (100%) rename third_party/libassimp/code/{ => Common}/Importer.cpp (98%) rename third_party/libassimp/code/{ => Common}/Importer.h (99%) rename third_party/libassimp/code/{ => Common}/ImporterRegistry.cpp (85%) rename third_party/libassimp/code/{ => Common}/PolyTools.h (99%) rename third_party/libassimp/code/{ => Common}/PostStepRegistry.cpp (83%) rename third_party/libassimp/code/{ => Common}/RemoveComments.cpp (99%) rename third_party/libassimp/code/{ => Common}/SGSpatialSort.cpp (99%) rename third_party/libassimp/code/{ => Common}/SceneCombiner.cpp (97%) rename third_party/libassimp/code/{ => Common}/ScenePreprocessor.cpp (99%) rename third_party/libassimp/code/{ => Common}/ScenePreprocessor.h (99%) rename third_party/libassimp/code/{ => Common}/ScenePrivate.h (98%) rename third_party/libassimp/code/{ => Common}/SkeletonMeshBuilder.cpp (99%) rename third_party/libassimp/code/{ => Common}/SpatialSort.cpp (99%) rename third_party/libassimp/code/{ => Common}/SplitByBoneCountProcess.cpp (99%) rename third_party/libassimp/code/{ => Common}/SplitByBoneCountProcess.h (99%) rename third_party/libassimp/code/{ => Common}/StandardShapes.cpp (95%) rename third_party/libassimp/code/{ => Common}/StdOStreamLogStream.h (98%) rename third_party/libassimp/code/{ => Common}/Subdivision.cpp (99%) rename third_party/libassimp/code/{ => Common}/TargetAnimation.cpp (99%) rename third_party/libassimp/code/{ => Common}/TargetAnimation.h (99%) rename third_party/libassimp/code/{ => Common}/Version.cpp (96%) rename third_party/libassimp/code/{ => Common}/VertexTriangleAdjacency.cpp (99%) rename third_party/libassimp/code/{ => Common}/VertexTriangleAdjacency.h (99%) rename third_party/libassimp/code/{ => Common}/Win32DebugLogStream.h (98%) create mode 100644 third_party/libassimp/code/Common/ZipArchiveIOSystem.cpp rename third_party/libassimp/code/{ => Common}/assbin_chunks.h (100%) rename third_party/libassimp/code/{ => Common}/scene.cpp (99%) rename third_party/libassimp/code/{ => Common}/simd.cpp (98%) rename third_party/libassimp/code/{ => Common}/simd.h (98%) delete mode 100644 third_party/libassimp/code/D3MFOpcPackage.cpp rename third_party/libassimp/code/{ => DXF}/DXFHelper.h (99%) rename third_party/libassimp/code/{ => DXF}/DXFLoader.cpp (99%) rename third_party/libassimp/code/{ => DXF}/DXFLoader.h (99%) rename third_party/libassimp/code/{ => FBX}/FBXAnimation.cpp (98%) rename third_party/libassimp/code/{ => FBX}/FBXBinaryTokenizer.cpp (96%) rename third_party/libassimp/code/{ => FBX}/FBXCommon.h (98%) rename third_party/libassimp/code/{ => FBX}/FBXCompileConfig.h (98%) create mode 100644 third_party/libassimp/code/FBX/FBXConverter.cpp rename third_party/libassimp/code/{ => FBX}/FBXConverter.h (90%) rename third_party/libassimp/code/{ => FBX}/FBXDeformer.cpp (70%) rename third_party/libassimp/code/{ => FBX}/FBXDocument.cpp (97%) rename third_party/libassimp/code/{ => FBX}/FBXDocument.h (93%) rename third_party/libassimp/code/{ => FBX}/FBXDocumentUtil.cpp (99%) rename third_party/libassimp/code/{ => FBX}/FBXDocumentUtil.h (95%) rename third_party/libassimp/code/{ => FBX}/FBXExportNode.cpp (97%) rename third_party/libassimp/code/{ => FBX}/FBXExportNode.h (94%) rename third_party/libassimp/code/{ => FBX}/FBXExportProperty.cpp (60%) rename third_party/libassimp/code/{ => FBX}/FBXExportProperty.h (76%) rename third_party/libassimp/code/{ => FBX}/FBXExporter.cpp (91%) rename third_party/libassimp/code/{ => FBX}/FBXExporter.h (98%) rename third_party/libassimp/code/{ => FBX}/FBXImportSettings.h (87%) rename third_party/libassimp/code/{ => FBX}/FBXImporter.cpp (90%) rename third_party/libassimp/code/{ => FBX}/FBXImporter.h (98%) rename third_party/libassimp/code/{ => FBX}/FBXMaterial.cpp (78%) rename third_party/libassimp/code/{ => FBX}/FBXMeshGeometry.cpp (86%) rename third_party/libassimp/code/{ => FBX}/FBXMeshGeometry.h (80%) rename third_party/libassimp/code/{ => FBX}/FBXModel.cpp (99%) rename third_party/libassimp/code/{ => FBX}/FBXNodeAttribute.cpp (99%) rename third_party/libassimp/code/{ => FBX}/FBXParser.cpp (99%) rename third_party/libassimp/code/{ => FBX}/FBXParser.h (99%) rename third_party/libassimp/code/{ => FBX}/FBXProperties.cpp (99%) rename third_party/libassimp/code/{ => FBX}/FBXProperties.h (99%) rename third_party/libassimp/code/{ => FBX}/FBXTokenizer.cpp (99%) rename third_party/libassimp/code/{ => FBX}/FBXTokenizer.h (96%) create mode 100644 third_party/libassimp/code/FBX/FBXUtil.cpp rename third_party/libassimp/code/{ => FBX}/FBXUtil.h (75%) delete mode 100644 third_party/libassimp/code/FBXConverter.cpp delete mode 100644 third_party/libassimp/code/FBXUtil.cpp rename third_party/libassimp/code/{ => HMP}/HMPFileData.h (99%) rename third_party/libassimp/code/{ => HMP}/HMPLoader.cpp (99%) rename third_party/libassimp/code/{ => HMP}/HMPLoader.h (98%) rename third_party/libassimp/code/{ => HMP}/HalfLifeFileData.h (99%) rename third_party/libassimp/code/{ => Irr}/IRRLoader.cpp (97%) rename third_party/libassimp/code/{ => Irr}/IRRLoader.h (94%) rename third_party/libassimp/code/{ => Irr}/IRRMeshLoader.cpp (99%) rename third_party/libassimp/code/{ => Irr}/IRRMeshLoader.h (98%) rename third_party/libassimp/code/{ => Irr}/IRRShared.cpp (99%) rename third_party/libassimp/code/{ => Irr}/IRRShared.h (100%) rename third_party/libassimp/code/{ => LWO}/LWOAnimation.cpp (99%) rename third_party/libassimp/code/{ => LWO}/LWOAnimation.h (99%) rename third_party/libassimp/code/{ => LWO}/LWOBLoader.cpp (99%) rename third_party/libassimp/code/{ => LWO}/LWOFileData.h (99%) rename third_party/libassimp/code/{ => LWO}/LWOLoader.cpp (99%) rename third_party/libassimp/code/{ => LWO}/LWOLoader.h (99%) rename third_party/libassimp/code/{ => LWO}/LWOMaterial.cpp (99%) rename third_party/libassimp/code/{ => LWS}/LWSLoader.cpp (99%) rename third_party/libassimp/code/{ => LWS}/LWSLoader.h (99%) rename third_party/libassimp/code/{ => MD2}/MD2FileData.h (99%) rename third_party/libassimp/code/{ => MD2}/MD2Loader.cpp (99%) rename third_party/libassimp/code/{ => MD2}/MD2Loader.h (99%) rename third_party/libassimp/code/{ => MD2}/MD2NormalTable.h (99%) rename third_party/libassimp/code/{ => MD3}/MD3FileData.h (97%) rename third_party/libassimp/code/{ => MD3}/MD3Loader.cpp (97%) rename third_party/libassimp/code/{ => MD3}/MD3Loader.h (99%) rename third_party/libassimp/code/{ => MD4}/MD4FileData.h (100%) rename third_party/libassimp/code/{ => MD5}/MD5Loader.cpp (97%) rename third_party/libassimp/code/{ => MD5}/MD5Loader.h (99%) rename third_party/libassimp/code/{ => MD5}/MD5Parser.cpp (99%) rename third_party/libassimp/code/{ => MD5}/MD5Parser.h (99%) rename third_party/libassimp/code/{ => MDC}/MDCFileData.h (99%) rename third_party/libassimp/code/{ => MDC}/MDCLoader.cpp (99%) rename third_party/libassimp/code/{ => MDC}/MDCLoader.h (99%) rename third_party/libassimp/code/{ => MDC}/MDCNormalTable.h (100%) rename third_party/libassimp/code/{ => MDL}/MDLDefaultColorMap.h (99%) rename third_party/libassimp/code/{ => MDL}/MDLFileData.h (99%) rename third_party/libassimp/code/{ => MDL}/MDLLoader.cpp (99%) rename third_party/libassimp/code/{ => MDL}/MDLLoader.h (99%) rename third_party/libassimp/code/{ => MDL}/MDLMaterialLoader.cpp (99%) rename third_party/libassimp/code/{ => MMD}/MMDCpp14.h (98%) rename third_party/libassimp/code/{ => MMD}/MMDImporter.cpp (98%) rename third_party/libassimp/code/{ => MMD}/MMDImporter.h (100%) rename third_party/libassimp/code/{ => MMD}/MMDPmdParser.h (99%) rename third_party/libassimp/code/{ => MMD}/MMDPmxParser.cpp (99%) rename third_party/libassimp/code/{ => MMD}/MMDPmxParser.h (99%) rename third_party/libassimp/code/{ => MMD}/MMDVmdParser.h (99%) rename third_party/libassimp/code/{ => MS3D}/MS3DLoader.cpp (99%) rename third_party/libassimp/code/{ => MS3D}/MS3DLoader.h (99%) rename third_party/libassimp/code/{ => Material}/MaterialSystem.cpp (95%) rename third_party/libassimp/code/{ => Material}/MaterialSystem.h (98%) rename third_party/libassimp/code/{ => NDO}/NDOLoader.cpp (99%) rename third_party/libassimp/code/{ => NDO}/NDOLoader.h (100%) rename third_party/libassimp/code/{ => NFF}/NFFLoader.cpp (99%) rename third_party/libassimp/code/{ => NFF}/NFFLoader.h (99%) rename third_party/libassimp/code/{ => OFF}/OFFLoader.cpp (99%) rename third_party/libassimp/code/{ => OFF}/OFFLoader.h (98%) rename third_party/libassimp/code/{ => Obj}/ObjExporter.cpp (99%) rename third_party/libassimp/code/{ => Obj}/ObjExporter.h (99%) rename third_party/libassimp/code/{ => Obj}/ObjFileData.h (98%) rename third_party/libassimp/code/{ => Obj}/ObjFileImporter.cpp (93%) rename third_party/libassimp/code/{ => Obj}/ObjFileImporter.h (99%) rename third_party/libassimp/code/{ => Obj}/ObjFileMtlImporter.cpp (99%) rename third_party/libassimp/code/{ => Obj}/ObjFileMtlImporter.h (99%) rename third_party/libassimp/code/{ => Obj}/ObjFileParser.cpp (95%) rename third_party/libassimp/code/{ => Obj}/ObjFileParser.h (98%) rename third_party/libassimp/code/{ => Obj}/ObjTools.h (99%) rename third_party/libassimp/code/{ => Ogre}/OgreBinarySerializer.cpp (99%) rename third_party/libassimp/code/{ => Ogre}/OgreBinarySerializer.h (99%) rename third_party/libassimp/code/{ => Ogre}/OgreImporter.cpp (99%) rename third_party/libassimp/code/{ => Ogre}/OgreImporter.h (99%) rename third_party/libassimp/code/{ => Ogre}/OgreMaterial.cpp (99%) rename third_party/libassimp/code/{ => Ogre}/OgreParsingUtils.h (99%) rename third_party/libassimp/code/{ => Ogre}/OgreStructs.cpp (99%) rename third_party/libassimp/code/{ => Ogre}/OgreStructs.h (99%) rename third_party/libassimp/code/{ => Ogre}/OgreXmlSerializer.cpp (99%) rename third_party/libassimp/code/{ => Ogre}/OgreXmlSerializer.h (99%) rename third_party/libassimp/code/{ => OpenGEX}/OpenGEXExporter.cpp (98%) rename third_party/libassimp/code/{ => OpenGEX}/OpenGEXExporter.h (98%) rename third_party/libassimp/code/{ => OpenGEX}/OpenGEXImporter.cpp (99%) rename third_party/libassimp/code/{ => OpenGEX}/OpenGEXImporter.h (99%) rename third_party/libassimp/code/{ => OpenGEX}/OpenGEXStructs.h (99%) rename third_party/libassimp/code/{ => Ply}/PlyExporter.cpp (99%) rename third_party/libassimp/code/{ => Ply}/PlyExporter.h (98%) rename third_party/libassimp/code/{ => Ply}/PlyLoader.cpp (99%) rename third_party/libassimp/code/{ => Ply}/PlyLoader.h (99%) rename third_party/libassimp/code/{ => Ply}/PlyParser.cpp (99%) rename third_party/libassimp/code/{ => Ply}/PlyParser.h (99%) rename third_party/libassimp/code/{ => PostProcessing}/CalcTangentsProcess.cpp (98%) rename third_party/libassimp/code/{ => PostProcessing}/CalcTangentsProcess.h (97%) rename third_party/libassimp/code/{ => PostProcessing}/ComputeUVMappingProcess.cpp (99%) rename third_party/libassimp/code/{ => PostProcessing}/ComputeUVMappingProcess.h (98%) rename third_party/libassimp/code/{ => PostProcessing}/ConvertToLHProcess.cpp (83%) rename third_party/libassimp/code/{ => PostProcessing}/ConvertToLHProcess.h (98%) rename third_party/libassimp/code/{ => PostProcessing}/DeboneProcess.cpp (99%) rename third_party/libassimp/code/{ => PostProcessing}/DeboneProcess.h (96%) rename third_party/libassimp/code/{ => PostProcessing}/DropFaceNormalsProcess.cpp (99%) rename third_party/libassimp/code/{ => PostProcessing}/DropFaceNormalsProcess.h (96%) rename third_party/libassimp/code/{ => PostProcessing}/EmbedTexturesProcess.cpp (91%) rename third_party/libassimp/code/{ => PostProcessing}/EmbedTexturesProcess.h (97%) rename third_party/libassimp/code/{ => PostProcessing}/FindDegenerates.cpp (99%) rename third_party/libassimp/code/{ => PostProcessing}/FindDegenerates.h (98%) rename third_party/libassimp/code/{ => PostProcessing}/FindInstancesProcess.cpp (92%) rename third_party/libassimp/code/{ => PostProcessing}/FindInstancesProcess.h (97%) rename third_party/libassimp/code/{ => PostProcessing}/FindInvalidDataProcess.cpp (85%) rename third_party/libassimp/code/{ => PostProcessing}/FindInvalidDataProcess.h (89%) rename third_party/libassimp/code/{ => PostProcessing}/FixNormalsStep.cpp (99%) rename third_party/libassimp/code/{ => PostProcessing}/FixNormalsStep.h (97%) create mode 100644 third_party/libassimp/code/PostProcessing/GenBoundingBoxesProcess.cpp create mode 100644 third_party/libassimp/code/PostProcessing/GenBoundingBoxesProcess.h rename third_party/libassimp/code/{ => PostProcessing}/GenFaceNormalsProcess.cpp (99%) rename third_party/libassimp/code/{ => PostProcessing}/GenFaceNormalsProcess.h (97%) rename third_party/libassimp/code/{ => PostProcessing}/GenVertexNormalsProcess.cpp (99%) rename third_party/libassimp/code/{ => PostProcessing}/GenVertexNormalsProcess.h (93%) rename third_party/libassimp/code/{ => PostProcessing}/ImproveCacheLocality.cpp (89%) rename third_party/libassimp/code/{ => PostProcessing}/ImproveCacheLocality.h (95%) rename third_party/libassimp/code/{ => PostProcessing}/JoinVerticesProcess.cpp (93%) rename third_party/libassimp/code/{ => PostProcessing}/JoinVerticesProcess.h (96%) rename third_party/libassimp/code/{ => PostProcessing}/LimitBoneWeightsProcess.cpp (99%) rename third_party/libassimp/code/{ => PostProcessing}/LimitBoneWeightsProcess.h (92%) rename third_party/libassimp/code/{ => PostProcessing}/MakeVerboseFormat.cpp (88%) rename third_party/libassimp/code/{ => PostProcessing}/MakeVerboseFormat.h (91%) rename third_party/libassimp/code/{ => PostProcessing}/OptimizeGraph.cpp (99%) rename third_party/libassimp/code/{ => PostProcessing}/OptimizeGraph.h (92%) rename third_party/libassimp/code/{ => PostProcessing}/OptimizeMeshes.cpp (99%) rename third_party/libassimp/code/{ => PostProcessing}/OptimizeMeshes.h (97%) rename third_party/libassimp/code/{ => PostProcessing}/PretransformVertices.cpp (99%) rename third_party/libassimp/code/{ => PostProcessing}/PretransformVertices.h (96%) rename third_party/libassimp/code/{ => PostProcessing}/ProcessHelper.cpp (99%) rename third_party/libassimp/code/{ => PostProcessing}/ProcessHelper.h (99%) rename third_party/libassimp/code/{ => PostProcessing}/RemoveRedundantMaterials.cpp (96%) rename third_party/libassimp/code/{ => PostProcessing}/RemoveRedundantMaterials.h (91%) rename third_party/libassimp/code/{ => PostProcessing}/RemoveVCProcess.cpp (99%) rename third_party/libassimp/code/{ => PostProcessing}/RemoveVCProcess.h (98%) create mode 100644 third_party/libassimp/code/PostProcessing/ScaleProcess.cpp rename third_party/libassimp/code/{ => PostProcessing}/ScaleProcess.h (83%) rename third_party/libassimp/code/{ => PostProcessing}/SortByPTypeProcess.cpp (89%) rename third_party/libassimp/code/{ => PostProcessing}/SortByPTypeProcess.h (94%) rename third_party/libassimp/code/{ => PostProcessing}/SplitLargeMeshes.cpp (99%) rename third_party/libassimp/code/{ => PostProcessing}/SplitLargeMeshes.h (98%) rename third_party/libassimp/code/{ => PostProcessing}/TextureTransform.cpp (99%) rename third_party/libassimp/code/{ => PostProcessing}/TextureTransform.h (98%) rename third_party/libassimp/code/{ => PostProcessing}/TriangulateProcess.cpp (99%) rename third_party/libassimp/code/{ => PostProcessing}/TriangulateProcess.h (95%) rename third_party/libassimp/code/{ => PostProcessing}/ValidateDataStructure.cpp (91%) rename third_party/libassimp/code/{ => PostProcessing}/ValidateDataStructure.h (98%) rename third_party/libassimp/code/{ => Q3BSP}/Q3BSPFileData.h (99%) rename third_party/libassimp/code/{ => Q3BSP}/Q3BSPFileImporter.cpp (97%) rename third_party/libassimp/code/{ => Q3BSP}/Q3BSPFileImporter.h (91%) rename third_party/libassimp/code/{ => Q3BSP}/Q3BSPFileParser.cpp (97%) rename third_party/libassimp/code/{ => Q3BSP}/Q3BSPFileParser.h (91%) delete mode 100644 third_party/libassimp/code/Q3BSPZipArchive.cpp delete mode 100644 third_party/libassimp/code/Q3BSPZipArchive.h rename third_party/libassimp/code/{ => Q3D}/Q3DLoader.cpp (98%) rename third_party/libassimp/code/{ => Q3D}/Q3DLoader.h (99%) rename third_party/libassimp/code/{ => Raw}/RawLoader.cpp (99%) rename third_party/libassimp/code/{ => Raw}/RawLoader.h (98%) rename third_party/libassimp/code/{ => SIB}/SIBImporter.cpp (99%) rename third_party/libassimp/code/{ => SIB}/SIBImporter.h (99%) rename third_party/libassimp/code/{ => SMD}/SMDLoader.cpp (99%) rename third_party/libassimp/code/{ => SMD}/SMDLoader.h (99%) rename third_party/libassimp/code/{ => STL}/STLExporter.cpp (97%) rename third_party/libassimp/code/{ => STL}/STLExporter.h (98%) rename third_party/libassimp/code/{ => STL}/STLLoader.cpp (98%) rename third_party/libassimp/code/{ => STL}/STLLoader.h (98%) rename third_party/libassimp/code/{ => Step}/STEPFile.h (99%) rename third_party/libassimp/code/{ => Step}/StepExporter.cpp (96%) rename third_party/libassimp/code/{ => Step}/StepExporter.h (98%) rename third_party/libassimp/code/{ => Terragen}/TerragenLoader.cpp (99%) rename third_party/libassimp/code/{ => Terragen}/TerragenLoader.h (98%) rename third_party/libassimp/code/{ => Unreal}/UnrealLoader.cpp (99%) rename third_party/libassimp/code/{ => Unreal}/UnrealLoader.h (98%) rename third_party/libassimp/code/{ => X}/XFileExporter.cpp (98%) rename third_party/libassimp/code/{ => X}/XFileExporter.h (99%) rename third_party/libassimp/code/{ => X}/XFileHelper.h (99%) rename third_party/libassimp/code/{ => X}/XFileImporter.cpp (98%) rename third_party/libassimp/code/{ => X}/XFileImporter.h (98%) rename third_party/libassimp/code/{ => X}/XFileParser.cpp (98%) rename third_party/libassimp/code/{ => X}/XFileParser.h (99%) rename third_party/libassimp/code/{ => X3D}/FIReader.cpp (99%) mode change 100755 => 100644 rename third_party/libassimp/code/{ => X3D}/FIReader.hpp (97%) rename third_party/libassimp/code/{ => X3D}/X3DExporter.cpp (99%) rename third_party/libassimp/code/{ => X3D}/X3DExporter.hpp (100%) rename third_party/libassimp/code/{ => X3D}/X3DImporter.cpp (97%) rename third_party/libassimp/code/{ => X3D}/X3DImporter.hpp (99%) rename third_party/libassimp/code/{ => X3D}/X3DImporter_Geometry2D.cpp (99%) rename third_party/libassimp/code/{ => X3D}/X3DImporter_Geometry3D.cpp (99%) rename third_party/libassimp/code/{ => X3D}/X3DImporter_Group.cpp (99%) rename third_party/libassimp/code/{ => X3D}/X3DImporter_Light.cpp (99%) rename third_party/libassimp/code/{ => X3D}/X3DImporter_Macro.hpp (99%) rename third_party/libassimp/code/{ => X3D}/X3DImporter_Metadata.cpp (99%) rename third_party/libassimp/code/{ => X3D}/X3DImporter_Networking.cpp (98%) rename third_party/libassimp/code/{ => X3D}/X3DImporter_Node.hpp (99%) rename third_party/libassimp/code/{ => X3D}/X3DImporter_Postprocess.cpp (94%) rename third_party/libassimp/code/{ => X3D}/X3DImporter_Rendering.cpp (99%) rename third_party/libassimp/code/{ => X3D}/X3DImporter_Shape.cpp (99%) rename third_party/libassimp/code/{ => X3D}/X3DImporter_Texturing.cpp (99%) rename third_party/libassimp/code/{ => X3D}/X3DVocabulary.cpp (99%) rename third_party/libassimp/code/{ => XGL}/XGLLoader.cpp (98%) rename third_party/libassimp/code/{ => XGL}/XGLLoader.h (99%) rename third_party/libassimp/code/{ => glTF}/glTFAsset.h (95%) rename third_party/libassimp/code/{ => glTF}/glTFAsset.inl (88%) rename third_party/libassimp/code/{ => glTF}/glTFAssetWriter.h (98%) rename third_party/libassimp/code/{ => glTF}/glTFAssetWriter.inl (96%) create mode 100644 third_party/libassimp/code/glTF/glTFCommon.cpp create mode 100644 third_party/libassimp/code/glTF/glTFCommon.h rename third_party/libassimp/code/{ => glTF}/glTFExporter.cpp (98%) rename third_party/libassimp/code/{ => glTF}/glTFExporter.h (99%) rename third_party/libassimp/code/{ => glTF}/glTFImporter.cpp (92%) mode change 100755 => 100644 rename third_party/libassimp/code/{ => glTF}/glTFImporter.h (98%) rename third_party/libassimp/code/{ => glTF2}/glTF2Asset.h (94%) rename third_party/libassimp/code/{ => glTF2}/glTF2Asset.inl (87%) mode change 100755 => 100644 rename third_party/libassimp/code/{ => glTF2}/glTF2AssetWriter.h (98%) rename third_party/libassimp/code/{ => glTF2}/glTF2AssetWriter.inl (98%) rename third_party/libassimp/code/{ => glTF2}/glTF2Exporter.cpp (96%) rename third_party/libassimp/code/{ => glTF2}/glTF2Exporter.h (99%) rename third_party/libassimp/code/{ => glTF2}/glTF2Importer.cpp (82%) mode change 100755 => 100644 rename third_party/libassimp/code/{ => glTF2}/glTF2Importer.h (98%) delete mode 100644 third_party/libassimp/code/makefile.mingw delete mode 100644 third_party/libassimp/contrib/gtest/.gitignore create mode 100644 third_party/libassimp/contrib/stb_image/stb_image.h delete mode 100644 third_party/libassimp/contrib/zip/.gitignore create mode 100755 third_party/libassimp/contrib/zip/.travis.sh delete mode 100644 third_party/libassimp/contrib/zip/appveyor.yml create mode 100755 third_party/libassimp/contrib/zip/cmake/asan-wrapper create mode 100644 third_party/libassimp/contrib/zip/cmake/cmake_uninstall.cmake.in create mode 100644 third_party/libassimp/contrib/zip/test/test_miniz.c create mode 100644 third_party/libassimp/include/assimp/ZipArchiveIOSystem.h rename third_party/libassimp/{code/ScaleProcess.cpp => include/assimp/aabb.h} (50%) delete mode 100644 third_party/libassimp/packaging/windows-innosetup/script.iss create mode 100644 third_party/libassimp/packaging/windows-innosetup/script_x64.iss create mode 100644 third_party/libassimp/packaging/windows-innosetup/script_x86.iss create mode 100644 third_party/libassimp/port/PyAssimp/README.md create mode 100644 third_party/libassimp/port/iOS/IPHONEOS_ARM64E_TOOLCHAIN.cmake create mode 100644 third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiProgressHandler.java diff --git a/third_party/libassimp/.editorconfig b/third_party/libassimp/.editorconfig new file mode 100644 index 0000000000..d95a7e3dc0 --- /dev/null +++ b/third_party/libassimp/.editorconfig @@ -0,0 +1,22 @@ +# See for details + +root = true + +[CMakeLists.txt,*.cmake{,.in}] +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_size = 2 +indent_style = space + +[*.h.in] +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_size = 4 +indent_style = space + +[*.txt] +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true diff --git a/third_party/libassimp/.gitignore b/third_party/libassimp/.gitignore index 466f62d745..9dcb6623d9 100644 --- a/third_party/libassimp/.gitignore +++ b/third_party/libassimp/.gitignore @@ -1,3 +1,4 @@ +.idea build .project *.kdev4* @@ -6,11 +7,29 @@ build *.sln *.ncb *.vcproj +*.vcxproj.user +*.VC.db +*.VC.db-shm +*.VC.db-wal +*.VC.opendb +*.ipch # Output bin/ lib/ +# QtCreator +CMakeLists.txt.user + +# Generated +assimp.pc +assimp.aps +revision.h +contrib/zlib/zconf.h +contrib/zlib/zlib.pc +include/assimp/config.h +unit.vcxproj.user + # CMake CMakeCache.txt CMakeFiles @@ -19,9 +38,67 @@ cmake_uninstall.cmake *.dir/ assimp-config.cmake assimp-config-version.cmake +assimpTargets*.cmake + +# MakeFile +Makefile +code/Makefile +test/Makefile +test/headercheck/Makefile +tools/assimp_cmd/Makefile # Tests test/results +test/readlinetest* # Python __pycache__ +*.log +*.vcxproj +*.filters +*.tlog +Assimp.sdf +test/gtest/tmp/gtest-gitupdate.cmake +test/gtest/tmp/gtest-gitclone.cmake +test/gtest/tmp/gtest-cfgcmd.txt.in +test/gtest/tmp/gtest-cfgcmd.txt +test/gtest/src/gtest-stamp/gtest-download.cmake +test/gtest/src/gtest-stamp/gtest-configure.cmake +test/gtest/src/gtest-stamp/gtest-build.cmake +test/gtest/src/gtest-stamp/Debug/gtest-patch +*.cache +test/gtest/src/gtest-stamp/Debug/gtest-build +*.suo +*.lib +test/gtest/src/gtest-stamp/Debug/ +tools/assimp_view/assimp_viewer.vcxproj.user +*.pyc + +# Unix editor backups +*~ +test/gtest/src/gtest-stamp/gtest-gitinfo.txt +test/gtest/src/gtest-stamp/gtest-gitclone-lastrun.txt +Assimp.opensdf +contrib/zlib/CTestTestfile.cmake +ipch/assimp_viewer-44bbbcd1/assimp_viewerd-ccc45335.ipch +bin64/assimp-vc140-mt.dll +bin64/assimp-vc140-mtd.dll +lib64/assimp-vc140-mt.exp +lib64/assimp-vc140-mtd.exp +lib64/assimp-vc140-mtd.ilk +lib64/assimp-vc140-mtd.pdb +bin64/assimp-vc120-mt.dll +bin64/assimp-vc120-mtd.dll +lib64/assimp-vc120-mtd.pdb +lib64/assimp-vc120-mtd.ilk +lib64/assimp-vc120-mtd.exp +lib64/assimp-vc120-mt.exp +xcuserdata + +cmake-build-debug +install_manifest.txt +tools/assimp_qt_viewer/moc_glview.cpp +tools/assimp_qt_viewer/moc_glview.cpp_parameters +tools/assimp_qt_viewer/moc_mainwindow.cpp +tools/assimp_qt_viewer/moc_mainwindow.cpp_parameters +tools/assimp_qt_viewer/ui_mainwindow.h diff --git a/third_party/libassimp/.travis.yml b/third_party/libassimp/.travis.yml deleted file mode 100644 index aa07c4f75f..0000000000 --- a/third_party/libassimp/.travis.yml +++ /dev/null @@ -1,19 +0,0 @@ -before_install: - - sudo apt-get install cmake - -env: - - TRAVIS_NO_EXPORT=YES - - TRAVIS_NO_EXPORT=NO - - TRAVIS_STATIC_BUILD=ON - - TRAVIS_STATIC_BUILD=OFF - -language: cpp - -compiler: - - gcc - - clang - -script: cmake -G "Unix Makefiles" -DASSIMP_ENABLE_BOOST_WORKAROUND=YES -DASSIMP_NO_EXPORT=$TRAVIS_NO_EXPORT -STATIC_BUILD=$TRAVIS_STATIC_BUILD && make - - - diff --git a/third_party/libassimp/BUILDBINARIES_EXAMPLE.bat b/third_party/libassimp/BUILDBINARIES_EXAMPLE.bat new file mode 100644 index 0000000000..2dd13a542a --- /dev/null +++ b/third_party/libassimp/BUILDBINARIES_EXAMPLE.bat @@ -0,0 +1,26 @@ +:: This is an example file to generate binaries using Windows Operating System +:: This script is configured to be executed from the source directory + +:: Compiled binaries will be placed in BINARIES_DIR\code\CONFIG + +:: NOTE +:: The build process will generate a config.h file that is placed in BINARIES_DIR\include +:: This file must be merged with SOURCE_DIR\include +:: You should write yourself a script that copies the files where you want them. +:: Also see: https://github.com/assimp/assimp/pull/2646 + +SET SOURCE_DIR=. + +:: For generators see "cmake --help" +SET GENERATOR=Visual Studio 15 2017 + +SET BINARIES_DIR="./BINARIES/Win32" +cmake CMakeLists.txt -G "%GENERATOR%" -S %SOURCE_DIR% -B %BINARIES_DIR% +cmake --build %BINARIES_DIR% --config release + +SET BINARIES_DIR="./BINARIES/x64" +cmake CMakeLists.txt -G "%GENERATOR% Win64" -S %SOURCE_DIR% -B %BINARIES_DIR% +cmake --build %BINARIES_DIR% --config debug +cmake --build %BINARIES_DIR% --config release + +PAUSE diff --git a/third_party/libassimp/Build.md b/third_party/libassimp/Build.md index d5b443a791..7c908606d2 100644 --- a/third_party/libassimp/Build.md +++ b/third_party/libassimp/Build.md @@ -1,32 +1,32 @@ -# Install CMake +# Build Instructions +## Install CMake Asset-Importer-Lib can be build for a lot of different platforms. We are using cmake to generate the build environment for these via cmake. So you have to make sure that you have a working cmake-installation on your system. You can download it at https://cmake.org/ or for linux install it via -``` +```bash sudo apt-get install cmake ``` -# Get the source +## Get the source Make sure you have a working git-installation. Open a command prompt and clone the Asset-Importer-Lib via: -``` +```bash git clone https://github.com/assimp/assimp.git ``` -# Build instructions for Windows with Visual-Studio +## Build instructions for Windows with Visual-Studio First you have to install Visual-Studio on your windows-system. You can get the Community-Version for free here: https://visualstudio.microsoft.com/de/downloads/ To generate the build environment for your IDE open a command prompt, navigate to your repo and type: -``` -> cmake CMakeLists.txt +```bash +cmake CMakeLists.txt ``` This will generate the project files for the visual studio. All dependencies used to build Asset-IMporter-Lib shall be part of the repo. If you want to use you own zlib.installation this is possible as well. Check the options for it. -# Build instructions for Windows with UWP -See https://stackoverflow.com/questions/40803170/cmake-uwp-using-cmake-to-build-universal-windows-app +## Build instructions for Windows with UWP +See - -# Build instrcutions for Linux / Unix +## Build instructions for Linux / Unix Open a terminal and got to your repository. You can generate the makefiles and build the library via: -``` +```bash cmake CMakeLists.txt make -j4 ``` @@ -34,7 +34,23 @@ The option -j descripes the number of parallel processes for the build. In this If you want to use a IDE for linux you can try QTCreator for instance. -# CMake build options +## Build instructions for MinGW + Older versions of MinGW's compiler (e.g. 5.1.0) do not support the -mbig_obj flag +required to compile some of assimp's files, especially for debug builds. +Version 7.3.0 of g++-mingw-w64 & gcc-mingw-w64 appears to work. + +Please see [CMake Cross Compiling](https://cmake.org/cmake/help/latest/manual/cmake-toolchains.7.html#cross-compiling) for general information on CMake Toolchains. + +Some users have had success building assimp using MinGW on Linux using [polly](https://github.com/ruslo/polly/). + +The following toolchain, which is not maintained by assimp, seems to work on Linux: [linux-mingw-w64-gnuxx11.cmake](https://github.com/ruslo/polly/blob/master/linux-mingw-w64-gnuxx11.cmake) + +The following toolchain may or may not be helpful for building assimp using MinGW on Windows (untested): + [mingw-cxx17.cmake](https://github.com/ruslo/polly/blob/master/mingw-cxx17.cmake) + +Besides the toolchain, compilation should be the same as for Linux / Unix. + +## CMake build options The cmake-build-environment provides options to configure the build. The following options can be used: - **BUILD_SHARED_LIBS ( default ON )**: Generation of shared libs ( dll for windows, so for Linux ). Set this to OFF to get a static lib. - **BUILD_FRAMEWORK ( default OFF, MacOnly)**: Build package as Mac OS X Framework bundle @@ -55,4 +71,3 @@ The cmake-build-environment provides options to configure the build. The followi - **INJECT_DEBUG_POSTFIX( default ON )**: Inject debug postfix in .a/.so lib names - **IGNORE_GIT_HASH ( default OFF )**: Don't call git to get the hash. - **ASSIMP_INSTALL_PDB ( default ON )**: Install MSVC debug files. - diff --git a/third_party/libassimp/CMakeLists.txt b/third_party/libassimp/CMakeLists.txt index 645d92689b..dcafb649f5 100644 --- a/third_party/libassimp/CMakeLists.txt +++ b/third_party/libassimp/CMakeLists.txt @@ -1,7 +1,7 @@ # Open Asset Import Library (assimp) # ---------------------------------------------------------------------- -# Copyright (c) 2006-2018, assimp team - +# Copyright (c) 2006-2019, assimp team +# # All rights reserved. # # Redistribution and use of this software in source and binary forms, @@ -34,9 +34,24 @@ # (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(CMAKE_LEGACY_CYGWIN_WIN32 0) # Remove when CMake >= 2.8.4 is required -CMAKE_MINIMUM_REQUIRED( VERSION 2.8 ) -PROJECT( Assimp ) +SET(CMAKE_POLICY_DEFAULT_CMP0074 NEW) + +CMAKE_MINIMUM_REQUIRED( VERSION 3.0 ) + +# Toggles the use of the hunter package manager +option(HUNTER_ENABLED "Enable Hunter package manager support" OFF) + +include("cmake/HunterGate.cmake") +HunterGate( + URL "https://github.com/ruslo/hunter/archive/v0.23.176.tar.gz" + SHA1 "2e9ae973d028660b735ac4c6142725ca36a0048a" +) + +IF(HUNTER_ENABLED) + add_definitions(-DASSIMP_USE_HUNTER) +ENDIF(HUNTER_ENABLED) + +PROJECT( Assimp VERSION 5.0.0 ) # All supported options ############################################### @@ -106,7 +121,7 @@ OPTION ( BUILD_DOCS OFF ) OPTION( INJECT_DEBUG_POSTFIX - "Inject debug postfix in .a/.so lib names" + "Inject debug postfix in .a/.so/.dll lib names" ON ) @@ -115,11 +130,12 @@ OPTION ( IGNORE_GIT_HASH OFF ) -IF (IOS) +IF (IOS AND NOT HUNTER_ENABLED) IF (NOT CMAKE_BUILD_TYPE) SET(CMAKE_BUILD_TYPE "Release") ENDIF (NOT CMAKE_BUILD_TYPE) -ENDIF (IOS) + ADD_DEFINITIONS(-DENABLE_BITCODE) +ENDIF (IOS AND NOT HUNTER_ENABLED) # Use subset of Windows.h if (WIN32) @@ -131,6 +147,10 @@ IF(MSVC) "Install MSVC debug files." ON ) + IF(NOT (MSVC_VERSION LESS 1900)) + # Multibyte character set is deprecated since at least MSVC2015 (possibly earlier) + ADD_DEFINITIONS( -DUNICODE -D_UNICODE ) + ENDIF() ENDIF(MSVC) IF (BUILD_FRAMEWORK) @@ -146,17 +166,17 @@ ELSE() ENDIF(NOT BUILD_SHARED_LIBS) # Define here the needed parameters -SET (ASSIMP_VERSION_MAJOR 4) -SET (ASSIMP_VERSION_MINOR 1) -SET (ASSIMP_VERSION_PATCH 0) +SET (ASSIMP_VERSION_MAJOR ${PROJECT_VERSION_MAJOR}) +SET (ASSIMP_VERSION_MINOR ${PROJECT_VERSION_MINOR}) +SET (ASSIMP_VERSION_PATCH ${PROJECT_VERSION_PATCH}) SET (ASSIMP_VERSION ${ASSIMP_VERSION_MAJOR}.${ASSIMP_VERSION_MINOR}.${ASSIMP_VERSION_PATCH}) -SET (ASSIMP_SOVERSION 4) -SET (PROJECT_VERSION "${ASSIMP_VERSION}") +SET (ASSIMP_SOVERSION 5) SET( ASSIMP_PACKAGE_VERSION "0" CACHE STRING "the package-specific version used for uploading the sources" ) - -# Enable C++1 globally -set_property( GLOBAL PROPERTY CXX_STANDARD 11 ) +if(NOT HUNTER_ENABLED) + # Enable C++11 support globally + set_property( GLOBAL PROPERTY CXX_STANDARD 11 ) +endif() IF(NOT IGNORE_GIT_HASH) # Get the current working branch @@ -196,8 +216,9 @@ CONFIGURE_FILE( ${CMAKE_CURRENT_BINARY_DIR}/include/assimp/config.h ) -INCLUDE_DIRECTORIES( +INCLUDE_DIRECTORIES( BEFORE ./ + code/ include ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR}/include @@ -216,9 +237,13 @@ ENDIF( UNIX ) # Grouped compiler settings IF ((CMAKE_C_COMPILER_ID MATCHES "GNU") AND NOT CMAKE_COMPILER_IS_MINGW) + IF(NOT HUNTER_ENABLED) + SET(CMAKE_CXX_FLAGS "-fPIC -std=c++0x ${CMAKE_CXX_FLAGS}") + SET(CMAKE_C_FLAGS "-fPIC ${CMAKE_C_FLAGS}") + ENDIF() # hide all not-exported symbols - SET(CMAKE_CXX_FLAGS "-g -fvisibility=hidden -fPIC -fno-strict-aliasing -Wall -std=c++0x ${CMAKE_CXX_FLAGS}") - SET(CMAKE_C_FLAGS "-fPIC -fno-strict-aliasing ${CMAKE_C_FLAGS}") + SET(CMAKE_CXX_FLAGS "-g -fvisibility=hidden -fno-strict-aliasing -Wall ${CMAKE_CXX_FLAGS}") + SET(CMAKE_C_FLAGS "-fno-strict-aliasing ${CMAKE_C_FLAGS}") SET(LIBSTDC++_LIBRARIES -lstdc++) ELSEIF(MSVC) # enable multi-core compilation with MSVC @@ -228,26 +253,39 @@ ELSEIF(MSVC) IF(MSVC12) ADD_COMPILE_OPTIONS(/wd4351) ENDIF() + SET(CMAKE_CXX_FLAGS_DEBUG "/D_DEBUG /MDd /Ob2 /DEBUG:FULL /Zi") ELSEIF ( "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang" ) - SET(CMAKE_CXX_FLAGS "-g -fvisibility=hidden -fPIC -fno-strict-aliasing -Wall -Wno-long-long -std=c++11 ${CMAKE_CXX_FLAGS}" ) - SET(CMAKE_C_FLAGS "-fPIC -fno-strict-aliasing ${CMAKE_C_FLAGS}") + IF(NOT HUNTER_ENABLED) + SET(CMAKE_CXX_FLAGS "-fPIC -std=c++11 ${CMAKE_CXX_FLAGS}") + SET(CMAKE_C_FLAGS "-fPIC ${CMAKE_C_FLAGS}") + ENDIF() + SET(CMAKE_CXX_FLAGS "-g -fvisibility=hidden -fno-strict-aliasing -Wall -Wno-long-long ${CMAKE_CXX_FLAGS}" ) + SET(CMAKE_C_FLAGS "-fno-strict-aliasing ${CMAKE_C_FLAGS}") ELSEIF( CMAKE_COMPILER_IS_MINGW ) - SET( CMAKE_CXX_FLAGS "-fvisibility=hidden -fno-strict-aliasing -Wall -Wno-long-long -std=c++11 -Wa,-mbig-obj ${CMAKE_CXX_FLAGS}" ) - SET(CMAKE_C_FLAGS "-fPIC -fno-strict-aliasing ${CMAKE_C_FLAGS} ") + IF (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.0) + message(FATAL_ERROR "MinGW is too old to be supported. Please update MinGW and try again.") + ELSEIF(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.3) + message(WARNING "MinGW is old, if you experience errors, update MinGW.") + ENDIF() + IF(NOT HUNTER_ENABLED) + SET(CMAKE_CXX_FLAGS "-std=c++11 ${CMAKE_CXX_FLAGS}") + SET(CMAKE_C_FLAGS "-fPIC ${CMAKE_C_FLAGS}") + ENDIF() + SET(CMAKE_CXX_FLAGS "-fvisibility=hidden -fno-strict-aliasing -Wall -Wno-long-long -Wa,-mbig-obj -O3 ${CMAKE_CXX_FLAGS}") + SET(CMAKE_C_FLAGS "-fno-strict-aliasing ${CMAKE_C_FLAGS}") ADD_DEFINITIONS( -U__STRICT_ANSI__ ) ENDIF() -IF ( IOS ) - -IF (CMAKE_BUILD_TYPE STREQUAL "Debug") - SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fembed-bitcode -Og") - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fembed-bitcode -Og") -ELSE() - SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fembed-bitcode -O3") - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fembed-bitcode -O3") -ENDIF() - -ENDIF( IOS ) +IF ( IOS AND NOT HUNTER_ENABLED) + IF (CMAKE_BUILD_TYPE STREQUAL "Debug") + SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fembed-bitcode -Og") + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fembed-bitcode -Og") + ELSE() + SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fembed-bitcode -O3") + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fembed-bitcode -O3") + # Experimental for pdb generation + ENDIF() +ENDIF( IOS AND NOT HUNTER_ENABLED) IF (ASSIMP_COVERALLS) MESSAGE(STATUS "Coveralls enabled") @@ -299,7 +337,9 @@ SET( ASSIMP_INCLUDE_INSTALL_DIR "include" CACHE STRING SET( ASSIMP_BIN_INSTALL_DIR "bin" CACHE STRING "Path the tool executables are installed to." ) -IF (CMAKE_BUILD_TYPE STREQUAL "Debug") +get_cmake_property(is_multi_config GENERATOR_IS_MULTI_CONFIG) + +IF (INJECT_DEBUG_POSTFIX AND (is_multi_config OR CMAKE_BUILD_TYPE STREQUAL "Debug")) SET(CMAKE_DEBUG_POSTFIX "d" CACHE STRING "Debug Postfix for lib, samples and tools") ELSE() SET(CMAKE_DEBUG_POSTFIX "" CACHE STRING "Debug Postfix for lib, samples and tools") @@ -312,20 +352,67 @@ IF (NOT TARGET uninstall) ADD_CUSTOM_TARGET(uninstall "${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake") ENDIF() -# 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}/assimpTargets.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/assimpTargets.cmake" @ONLY IMMEDIATE) -CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/assimpTargets-debug.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/assimpTargets-debug.cmake" @ONLY IMMEDIATE) -CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/assimpTargets-release.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/assimpTargets-release.cmake" @ONLY IMMEDIATE) -CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/assimp-config-version.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/assimp-config-version.cmake" @ONLY IMMEDIATE) -#we should generated these scripts after CMake VERSION 3.0.2 using export(EXPORT ...) and write_basic_package_version_file(...) -INSTALL(FILES - "${CMAKE_CURRENT_BINARY_DIR}/assimp-config.cmake" - "${CMAKE_CURRENT_BINARY_DIR}/assimp-config-version.cmake" - "${CMAKE_CURRENT_BINARY_DIR}/assimpTargets.cmake" - "${CMAKE_CURRENT_BINARY_DIR}/assimpTargets-debug.cmake" - "${CMAKE_CURRENT_BINARY_DIR}/assimpTargets-release.cmake" - DESTINATION "${ASSIMP_LIB_INSTALL_DIR}/cmake/assimp-${ASSIMP_VERSION_MAJOR}.${ASSIMP_VERSION_MINOR}" COMPONENT ${LIBASSIMP-DEV_COMPONENT}) +IF(HUNTER_ENABLED) + set(CONFIG_INSTALL_DIR "lib/cmake/${PROJECT_NAME}") + set(INCLUDE_INSTALL_DIR "include") + + set(GENERATED_DIR "${CMAKE_CURRENT_BINARY_DIR}/generated") + + # Configuration + set(VERSION_CONFIG "${GENERATED_DIR}/${PROJECT_NAME}ConfigVersion.cmake") + set(PROJECT_CONFIG "${GENERATED_DIR}/${PROJECT_NAME}Config.cmake") + set(TARGETS_EXPORT_NAME "${PROJECT_NAME}Targets") + set(NAMESPACE "${PROJECT_NAME}::") + + # Include module with fuction 'write_basic_package_version_file' + include(CMakePackageConfigHelpers) + + # Note: PROJECT_VERSION is used as a VERSION + write_basic_package_version_file("${VERSION_CONFIG}" COMPATIBILITY SameMajorVersion) + + # Use variables: + # * TARGETS_EXPORT_NAME + # * PROJECT_NAME + configure_package_config_file( + "cmake/assimp-hunter-config.cmake.in" + "${PROJECT_CONFIG}" + INSTALL_DESTINATION "${CONFIG_INSTALL_DIR}" + ) + + install( + FILES "${PROJECT_CONFIG}" "${VERSION_CONFIG}" + DESTINATION "${CONFIG_INSTALL_DIR}" + ) + + install( + EXPORT "${TARGETS_EXPORT_NAME}" + NAMESPACE "${NAMESPACE}" + DESTINATION "${CONFIG_INSTALL_DIR}" + ) +ELSE(HUNTER_ENABLED) + # 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}/assimpTargets.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/assimpTargets.cmake" @ONLY IMMEDIATE) + IF (is_multi_config) + CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/assimpTargets-debug.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/assimpTargets-debug.cmake" @ONLY IMMEDIATE) + CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/assimpTargets-release.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/assimpTargets-release.cmake" @ONLY IMMEDIATE) + SET(PACKAGE_TARGETS_FILE "${CMAKE_CURRENT_BINARY_DIR}/assimpTargets-debug.cmake" "${CMAKE_CURRENT_BINARY_DIR}/assimpTargets-release.cmake") + ELSEIF (CMAKE_BUILD_TYPE STREQUAL Debug) + CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/assimpTargets-debug.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/assimpTargets-debug.cmake" @ONLY IMMEDIATE) + SET(PACKAGE_TARGETS_FILE "${CMAKE_CURRENT_BINARY_DIR}/assimpTargets-debug.cmake") + ELSE() + CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/assimpTargets-release.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/assimpTargets-release.cmake" @ONLY IMMEDIATE) + SET(PACKAGE_TARGETS_FILE "${CMAKE_CURRENT_BINARY_DIR}/assimpTargets-release.cmake") + ENDIF() + CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/assimp-config-version.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/assimp-config-version.cmake" @ONLY IMMEDIATE) + #we should generated these scripts after CMake VERSION 3.0.2 using export(EXPORT ...) and write_basic_package_version_file(...) + INSTALL(FILES + "${CMAKE_CURRENT_BINARY_DIR}/assimp-config.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/assimp-config-version.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/assimpTargets.cmake" + ${PACKAGE_TARGETS_FILE} + DESTINATION "${ASSIMP_LIB_INSTALL_DIR}/cmake/assimp-${ASSIMP_VERSION_MAJOR}.${ASSIMP_VERSION_MINOR}" COMPONENT ${LIBASSIMP-DEV_COMPONENT}) +ENDIF(HUNTER_ENABLED) FIND_PACKAGE( DirectX ) @@ -340,39 +427,57 @@ ENDIF( SYSTEM_IRRXML ) # Search for external dependencies, and build them from source if not found # Search for zlib -IF ( NOT ASSIMP_BUILD_ZLIB ) - FIND_PACKAGE(ZLIB) -ENDIF( NOT ASSIMP_BUILD_ZLIB ) +IF(HUNTER_ENABLED) + hunter_add_package(ZLIB) + find_package(ZLIB CONFIG REQUIRED) -IF( NOT ZLIB_FOUND ) - MESSAGE(STATUS "compiling zlib from sources") - INCLUDE(CheckIncludeFile) - INCLUDE(CheckTypeSize) - INCLUDE(CheckFunctionExists) - # compile from sources - ADD_SUBDIRECTORY(contrib/zlib) - SET(ZLIB_FOUND 1) - SET(ZLIB_LIBRARIES zlibstatic) - SET(ZLIB_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/contrib/zlib ${CMAKE_CURRENT_BINARY_DIR}/contrib/zlib) - # need to ensure we don't link with system zlib or minizip as well. - SET(ASSIMP_BUILD_MINIZIP 1) -ELSE(NOT ZLIB_FOUND) - ADD_DEFINITIONS(-DASSIMP_BUILD_NO_OWN_ZLIB) - SET(ZLIB_LIBRARIES_LINKED -lz) -ENDIF(NOT ZLIB_FOUND) -INCLUDE_DIRECTORIES(${ZLIB_INCLUDE_DIR}) + add_definitions(-DASSIMP_BUILD_NO_OWN_ZLIB) + set(ZLIB_FOUND TRUE) + set(ZLIB_LIBRARIES ZLIB::zlib) + set(ASSIMP_BUILD_MINIZIP TRUE) +ELSE(HUNTER_ENABLED) + IF ( NOT ASSIMP_BUILD_ZLIB ) + FIND_PACKAGE(ZLIB) + ENDIF( NOT ASSIMP_BUILD_ZLIB ) -# Search for unzip -IF ( NOT IOS ) + IF( NOT ZLIB_FOUND ) + MESSAGE(STATUS "compiling zlib from sources") + INCLUDE(CheckIncludeFile) + INCLUDE(CheckTypeSize) + INCLUDE(CheckFunctionExists) + + # Explicitly turn off ASM686 and AMD64 cmake options. + # The AMD64 option causes a build failure on MSVC and the ASM builds seem to have problems: + # https://github.com/madler/zlib/issues/41#issuecomment-125848075 + # Also prevents these options from "polluting" the cmake options if assimp is being + # included as a submodule. + set( ASM686 FALSE CACHE INTERNAL "Override ZLIB flag to turn off assembly" FORCE ) + set( AMD64 FALSE CACHE INTERNAL "Override ZLIB flag to turn off assembly" FORCE ) + + # compile from sources + ADD_SUBDIRECTORY(contrib/zlib) + SET(ZLIB_FOUND 1) + SET(ZLIB_LIBRARIES zlibstatic) + SET(ZLIB_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/contrib/zlib ${CMAKE_CURRENT_BINARY_DIR}/contrib/zlib) + # need to ensure we don't link with system zlib or minizip as well. + SET(ASSIMP_BUILD_MINIZIP 1) + ELSE(NOT ZLIB_FOUND) + ADD_DEFINITIONS(-DASSIMP_BUILD_NO_OWN_ZLIB) + SET(ZLIB_LIBRARIES_LINKED -lz) + ENDIF(NOT ZLIB_FOUND) + INCLUDE_DIRECTORIES(${ZLIB_INCLUDE_DIR}) +ENDIF(HUNTER_ENABLED) + +IF( NOT IOS ) IF( NOT ASSIMP_BUILD_MINIZIP ) - use_pkgconfig(UNZIP minizip) + use_pkgconfig(UNZIP minizip) ENDIF( NOT ASSIMP_BUILD_MINIZIP ) ELSE ( NOT IOS ) - IF(NOT BUILD_SHARED_LIBS) + IF( NOT BUILD_SHARED_LIBS ) IF( NOT ASSIMP_BUILD_MINIZIP ) - use_pkgconfig(UNZIP minizip) + use_pkgconfig(UNZIP minizip) ENDIF( NOT ASSIMP_BUILD_MINIZIP ) - ENDIF (NOT BUILD_SHARED_LIBS) + ENDIF ( NOT BUILD_SHARED_LIBS ) ENDIF ( NOT IOS ) IF ( ASSIMP_NO_EXPORT ) @@ -446,26 +551,27 @@ ELSE (ASSIMP_BUILD_NONFREE_C4D_IMPORTER) ADD_DEFINITIONS( -DASSIMP_BUILD_NO_C4D_IMPORTER ) ENDIF (ASSIMP_BUILD_NONFREE_C4D_IMPORTER) -ADD_SUBDIRECTORY(contrib) +IF(NOT HUNTER_ENABLED) + ADD_SUBDIRECTORY(contrib) +ENDIF(NOT HUNTER_ENABLED) ADD_SUBDIRECTORY( code/ ) IF ( ASSIMP_BUILD_ASSIMP_TOOLS ) + # The viewer for windows only IF ( WIN32 AND DirectX_D3DX9_LIBRARY ) OPTION ( ASSIMP_BUILD_ASSIMP_VIEW "If the Assimp view tool is built. (requires DirectX)" ${DirectX_FOUND} ) IF ( ASSIMP_BUILD_ASSIMP_VIEW ) ADD_SUBDIRECTORY( tools/assimp_view/ ) ENDIF ( ASSIMP_BUILD_ASSIMP_VIEW ) ENDIF ( WIN32 AND DirectX_D3DX9_LIBRARY ) - + # Te command line tool ADD_SUBDIRECTORY( tools/assimp_cmd/ ) -IF (NOT IOS) - ADD_SUBDIRECTORY( tools/assimp_qt_viewer/ ) -ENDIF (NOT IOS) ENDIF ( ASSIMP_BUILD_ASSIMP_TOOLS ) IF ( ASSIMP_BUILD_SAMPLES) IF ( WIN32 ) ADD_SUBDIRECTORY( samples/SimpleTexturedOpenGL/ ) + ADD_SUBDIRECTORY( samples/SimpleTexturedDirectx11 ) ENDIF ( WIN32 ) ADD_SUBDIRECTORY( samples/SimpleOpenGL/ ) ENDIF ( ASSIMP_BUILD_SAMPLES ) @@ -531,18 +637,22 @@ if(WIN32) if (CMAKE_SIZEOF_VOID_P EQUAL 8) SET(BIN_DIR "${PROJECT_SOURCE_DIR}/bin64/") SET(LIB_DIR "${PROJECT_SOURCE_DIR}/lib64/") - elseif() + else() SET(BIN_DIR "${PROJECT_SOURCE_DIR}/bin32/") SET(LIB_DIR "${PROJECT_SOURCE_DIR}/lib32/") ENDIF() - IF(MSVC12) - SET(ASSIMP_MSVC_VERSION "vc120") - ELSEIF(MSVC14) - SET(ASSIMP_MSVC_VERSION "vc140") - ELSEIF(MSVC15) - SET(ASSIMP_MSVC_VERSION "vc141") - ENDIF(MSVC12) + IF(MSVC_TOOLSET_VERSION) + set(MSVC_PREFIX "vc${MSVC_TOOLSET_VERSION}") + ELSE() + IF(MSVC12) + SET(ASSIMP_MSVC_VERSION "vc120") + ELSEIF(MSVC14) + SET(ASSIMP_MSVC_VERSION "vc140") + ELSEIF(MSVC15) + SET(ASSIMP_MSVC_VERSION "vc141") + ENDIF(MSVC12) + ENDIF() IF(MSVC12 OR MSVC14 OR MSVC15 ) ADD_CUSTOM_TARGET(UpdateAssimpLibsDebugSymbolsAndDLLs COMMENT "Copying Assimp Libraries ..." VERBATIM) diff --git a/third_party/libassimp/INSTALL b/third_party/libassimp/INSTALL index 357918d6b2..350a5f1092 100644 --- a/third_party/libassimp/INSTALL +++ b/third_party/libassimp/INSTALL @@ -35,13 +35,16 @@ http://www.cmake.org/. For Unix: -1. cmake CMakeLists.txt -G 'Unix Makefiles' -2. make +1. mkdir build && cd build +2. cmake .. -G 'Unix Makefiles' +3. make -j4 For Windows: 1. Open a command prompt -2. cmake CMakeLists.txt -2. Open your default IDE and build it +2. mkdir build +3. cd build +4. cmake .. +5. cmake --build . For iOS: Just check the following project, which deploys a compiler toolchain for different iOS-versions: https://github.com/assimp/assimp/tree/master/port/iOS diff --git a/third_party/libassimp/Readme.md b/third_party/libassimp/Readme.md index 1ba026d5a9..52a195a649 100644 --- a/third_party/libassimp/Readme.md +++ b/third_party/libassimp/Readme.md @@ -1,7 +1,7 @@ Open Asset Import Library (assimp) ================================== A library to import and export various 3d-model-formats including scene-post-processing to generate missing render data. -### Current build status ### +### Current project status ### [![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) @@ -10,10 +10,15 @@ A library to import and export various 3d-model-formats including scene-post-pro [![Coverage Status](https://coveralls.io/repos/github/assimp/assimp/badge.svg?branch=master)](https://coveralls.io/github/assimp/assimp?branch=master) [![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) +[![Average time to resolve an issue](http://isitmaintained.com/badge/resolution/assimp/assimp.svg)](http://isitmaintained.com/project/assimp/assimp "Average time to resolve an issue") +[![Codacy Badge](https://api.codacy.com/project/badge/Grade/5be56faac64f46fc941ac890fb4febef)](https://www.codacy.com/app/kimkulling/assimp?utm_source=github.com&utm_medium=referral&utm_content=assimp/assimp&utm_campaign=Badge_Grade) +[![Total alerts](https://img.shields.io/lgtm/alerts/g/assimp/assimp.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/assimp/assimp/alerts/)
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. +[Check the latest doc](https://assimp-docs.readthedocs.io/en/latest/). + 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. This is the development repo containing the latest features and bugfixes. For productive use though, we recommend one of the stable releases available from [Github Assimp Releases](https://github.com/assimp/assimp/releases). @@ -96,7 +101,7 @@ __Importers__: Additionally, some formats are supported by dependency on non-free code or external SDKs (not built by default): -- [C4D](https://en.wikipedia.org/wiki/Cinema_4D) (https://github.com/assimp/assimp/wiki/Cinema4D-&-Melange) +- [C4D](https://en.wikipedia.org/wiki/Cinema_4D) (https://github.com/assimp/assimp/wiki/Cinema4D-&-Melange) IMporting geometry + node hierarchy are currently supported __Exporters__: @@ -120,17 +125,18 @@ Take a look into the https://github.com/assimp/assimp/blob/master/Build.md file. ### Ports ### * [Android](port/AndroidJNI/README.md) * [Python](port/PyAssimp/README.md) -* [.NET](port/AssimpNET/Readme.md) +* [.NET](https://github.com/kebby/assimp-net) * [Pascal](port/AssimpPascal/Readme.md) * [Javascript (Alpha)](https://github.com/makc/assimp2json) * [Unity 3d Plugin](https://www.assetstore.unity3d.com/en/#!/content/91777) * [JVM](https://github.com/kotlin-graphics/assimp) Full jvm port (current [status](https://github.com/kotlin-graphics/assimp/wiki/Status)) +* [HAXE-Port](https://github.com/longde123/assimp-haxe) The Assimp-HAXE-port. ### Other tools ### [open3mod](https://github.com/acgessler/open3mod) is a powerful 3D model viewer based on Assimp's import and export abilities. #### Repository structure #### -Open Asset Import Library is implemented in C++. The directory structure is: +Open Asset Import Library is implemented in C++. The directory structure looks like: /code Source code /contrib Third-party libraries @@ -143,6 +149,11 @@ Open Asset Import Library is implemented in C++. The directory structure is: /samples A small number of samples to illustrate possible use cases for Assimp +The source code is organized in the following way: + + code/Common The base implementation for importers and the infrastructure + code/PostProcessing The post-processing steps + code/ Implementation for import and export for the format ### Where to get help ### For more information, visit [our website](http://assimp.org/). Or check out the `./doc`- folder, which contains the official documentation in HTML format. diff --git a/third_party/libassimp/appveyor.yml b/third_party/libassimp/appveyor.yml deleted file mode 100644 index 2b5f212f9f..0000000000 --- a/third_party/libassimp/appveyor.yml +++ /dev/null @@ -1,67 +0,0 @@ -# AppVeyor file -# http://www.appveyor.com/docs/appveyor-yml - -# clone directory -clone_folder: c:\projects\assimp - -# branches to build -branches: - # whitelist - only: - - master - -matrix: - fast_finish: true - -image: - - Visual Studio 2013 - - Visual Studio 2015 - - Visual Studio 2017 - -platform: - - Win32 - - x64 - -configuration: Release - -install: - - set PATH=C:\Ruby24-x64\bin;%PATH% - - set CMAKE_DEFINES -DASSIMP_WERROR=ON - - if "%APPVEYOR_BUILD_WORKER_IMAGE%"=="Visual Studio 2013" set CMAKE_GENERATOR_NAME=Visual Studio 12 2013 - - if "%APPVEYOR_BUILD_WORKER_IMAGE%"=="Visual Studio 2015" set CMAKE_GENERATOR_NAME=Visual Studio 14 2015 - - if "%APPVEYOR_BUILD_WORKER_IMAGE%"=="Visual Studio 2017" set CMAKE_GENERATOR_NAME=Visual Studio 15 2017 - - if "%platform%"=="x64" set CMAKE_GENERATOR_NAME=%CMAKE_GENERATOR_NAME% Win64 - - cmake %CMAKE_DEFINES% -G "%CMAKE_GENERATOR_NAME%" - - set PATH=%PATH%;"C:\\Program Files (x86)\\Inno Setup 5" - - ps: Invoke-WebRequest -Uri https://download.microsoft.com/download/5/7/b/57b2947c-7221-4f33-b35e-2fc78cb10df4/vc_redist.x64.exe -OutFile .\packaging\windows-innosetup\vc_redist.x64.exe - - ps: Invoke-WebRequest -Uri https://download.microsoft.com/download/1/d/8/1d8137db-b5bb-4925-8c5d-927424a2e4de/vc_redist.x86.exe -OutFile .\packaging\windows-innosetup\vc_redist.x86.exe - -cache: - - code\assimp.dir\%CONFIGURATION% - - contrib\zlib\zlibstatic.dir\%CONFIGURATION% - - contrib\zlib\zlib.dir\%CONFIGURATION% - - tools\assimp_cmd\assimp_cmd.dir\%CONFIGURATION% - - tools\assimp_view\assimp_viewer.dir\%CONFIGURATION% - - test\unit.dir\%CONFIGURATION% - - bin\.mtime_cache - -before_build: - - ruby scripts\AppVeyor\mtime_cache -g scripts\AppVeyor\cacheglobs.txt -c bin\.mtime_cache\cache.json - -build: - parallel: true - project: Assimp.sln - -after_build: - - if "%APPVEYOR_BUILD_WORKER_IMAGE%"=="Visual Studio 2017" iscc packaging\windows-innosetup\script.iss - - 7z a assimp.7z bin\%CONFIGURATION%\* lib\%CONFIGURATION%\* - -test_script: - - cmd: bin\%CONFIGURATION%\unit.exe --gtest_output=xml:testout.xml - -on_finish: - - ps: (new-object net.webclient).UploadFile("https://ci.appveyor.com/api/testresults/junit/$($env:APPVEYOR_JOB_ID)", (Resolve-Path .\testout.xml)) - -artifacts: - - path: assimp.7z - name: assimp_lib diff --git a/third_party/libassimp/assimp.pc.in b/third_party/libassimp/assimp.pc.in index 02cf59dc4e..c659e19f2c 100644 --- a/third_party/libassimp/assimp.pc.in +++ b/third_party/libassimp/assimp.pc.in @@ -1,7 +1,7 @@ prefix=@CMAKE_INSTALL_PREFIX@ exec_prefix=@CMAKE_INSTALL_PREFIX@/ libdir=@CMAKE_INSTALL_PREFIX@/@ASSIMP_LIB_INSTALL_DIR@ -includedir=@CMAKE_INSTALL_PREFIX@/@ASSIMP_INCLUDE_INSTALL_DIR@ +includedir=@CMAKE_INSTALL_PREFIX@/../include/@ASSIMP_INCLUDE_INSTALL_DIR@ Name: @CMAKE_PROJECT_NAME@ Description: Import various well-known 3D model formats in an uniform manner. diff --git a/third_party/libassimp/assimpTargets-debug.cmake.in b/third_party/libassimp/assimpTargets-debug.cmake.in index a83e6c22de..1ebe2a6081 100644 --- a/third_party/libassimp/assimpTargets-debug.cmake.in +++ b/third_party/libassimp/assimpTargets-debug.cmake.in @@ -5,48 +5,79 @@ # Commands may need to know the format version. set(CMAKE_IMPORT_FILE_VERSION 1) +set(ASSIMP_BUILD_SHARED_LIBS @BUILD_SHARED_LIBS@) + if(MSVC) - if( MSVC70 OR MSVC71 ) - set(MSVC_PREFIX "vc70") - elseif( MSVC80 ) - set(MSVC_PREFIX "vc80") - elseif( MSVC90 ) - set(MSVC_PREFIX "vc90") - elseif( MSVC10 ) - set(MSVC_PREFIX "vc100") - elseif( MSVC11 ) - set(MSVC_PREFIX "vc110") - elseif( MSVC12 ) - set(MSVC_PREFIX "vc120") - elseif( MSVC14 ) - set(MSVC_PREFIX "vc140") + if(MSVC_TOOLSET_VERSION) + set(MSVC_PREFIX "vc${MSVC_TOOLSET_VERSION}") else() - set(MSVC_PREFIX "vc150") + if( MSVC70 OR MSVC71 ) + set(MSVC_PREFIX "vc70") + elseif( MSVC80 ) + set(MSVC_PREFIX "vc80") + elseif( MSVC90 ) + set(MSVC_PREFIX "vc90") + elseif( MSVC10 ) + set(MSVC_PREFIX "vc100") + elseif( MSVC11 ) + set(MSVC_PREFIX "vc110") + elseif( MSVC12 ) + set(MSVC_PREFIX "vc120") + elseif( MSVC_VERSION LESS 1910) + set(MSVC_PREFIX "vc140") + elseif( MSVC_VERSION LESS 1920) + set(MSVC_PREFIX "vc141") + elseif( MSVC_VERSION LESS 1930) + set(MSVC_PREFIX "vc142") + else() + set(MSVC_PREFIX "vc150") + endif() endif() set(ASSIMP_LIBRARY_SUFFIX "@ASSIMP_LIBRARY_SUFFIX@-${MSVC_PREFIX}-mt" CACHE STRING "the suffix for the assimp windows library" ) - set(sharedLibraryName "assimp${ASSIMP_LIBRARY_SUFFIX}@CMAKE_DEBUG_POSTFIX@@CMAKE_SHARED_LIBRARY_SUFFIX@") - set(importLibraryName "assimp${ASSIMP_LIBRARY_SUFFIX}@CMAKE_DEBUG_POSTFIX@@CMAKE_IMPORT_LIBRARY_SUFFIX@") + if(ASSIMP_BUILD_SHARED_LIBS) + set(sharedLibraryName "assimp${ASSIMP_LIBRARY_SUFFIX}@CMAKE_DEBUG_POSTFIX@@CMAKE_SHARED_LIBRARY_SUFFIX@") + set(importLibraryName "assimp${ASSIMP_LIBRARY_SUFFIX}@CMAKE_DEBUG_POSTFIX@@CMAKE_IMPORT_LIBRARY_SUFFIX@") - # Import target "assimp::assimp" for configuration "Debug" - set_property(TARGET assimp::assimp APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG) - set_target_properties(assimp::assimp PROPERTIES - IMPORTED_IMPLIB_DEBUG "${_IMPORT_PREFIX}/lib/${importLibraryName}" - IMPORTED_LOCATION_DEBUG "${_IMPORT_PREFIX}/bin/${sharedLibraryName}" - ) - list(APPEND _IMPORT_CHECK_TARGETS assimp::assimp ) - list(APPEND _IMPORT_CHECK_FILES_FOR_assimp::assimp "${_IMPORT_PREFIX}/lib/${importLibraryName}") - list(APPEND _IMPORT_CHECK_FILES_FOR_assimp::assimp "${_IMPORT_PREFIX}/bin/${sharedLibraryName}" ) + # Import target "assimp::assimp" for configuration "Debug" + set_property(TARGET assimp::assimp APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG) + set_target_properties(assimp::assimp PROPERTIES + IMPORTED_IMPLIB_DEBUG "${_IMPORT_PREFIX}/lib/${importLibraryName}" + IMPORTED_LOCATION_DEBUG "${_IMPORT_PREFIX}/bin/${sharedLibraryName}" + ) + list(APPEND _IMPORT_CHECK_TARGETS assimp::assimp ) + list(APPEND _IMPORT_CHECK_FILES_FOR_assimp::assimp "${_IMPORT_PREFIX}/lib/${importLibraryName}") + list(APPEND _IMPORT_CHECK_FILES_FOR_assimp::assimp "${_IMPORT_PREFIX}/bin/${sharedLibraryName}" ) + else() + set(staticLibraryName "assimp${ASSIMP_LIBRARY_SUFFIX}@CMAKE_DEBUG_POSTFIX@@CMAKE_STATIC_LIBRARY_SUFFIX@") + + # Import target "assimp::assimp" for configuration "Debug" + set_property(TARGET assimp::assimp APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG) + set_target_properties(assimp::assimp PROPERTIES + IMPORTED_LOCATION_DEBUG "${_IMPORT_PREFIX}/lib/${staticLibraryName}" + ) + list(APPEND _IMPORT_CHECK_TARGETS assimp::assimp ) + list(APPEND _IMPORT_CHECK_FILES_FOR_assimp::assimp "${_IMPORT_PREFIX}/lib/${staticLibraryName}") + endif() else() - set(ASSIMP_LIBRARY_SUFFIX "@ASSIMP_LIBRARY_SUFFIX@" CACHE STRING "the suffix for the openrave libraries" ) - set(sharedLibraryName "libassimp${ASSIMP_LIBRARY_SUFFIX}@CMAKE_DEBUG_POSTFIX@@CMAKE_SHARED_LIBRARY_SUFFIX@.@ASSIMP_VERSION_MAJOR@") - set_target_properties(assimp::assimp PROPERTIES - IMPORTED_SONAME_DEBUG "${sharedLibraryName}" - IMPORTED_LOCATION_DEBUG "${_IMPORT_PREFIX}/lib/${sharedLibraryName}" + set(ASSIMP_LIBRARY_SUFFIX "@ASSIMP_LIBRARY_SUFFIX@" CACHE STRING "the suffix for the assimp libraries" ) + if(ASSIMP_BUILD_SHARED_LIBS) + set(sharedLibraryName "libassimp${ASSIMP_LIBRARY_SUFFIX}@CMAKE_DEBUG_POSTFIX@@CMAKE_SHARED_LIBRARY_SUFFIX@.@ASSIMP_VERSION_MAJOR@") + set_target_properties(assimp::assimp PROPERTIES + IMPORTED_SONAME_DEBUG "${sharedLibraryName}" + IMPORTED_LOCATION_DEBUG "${_IMPORT_PREFIX}/lib/${sharedLibraryName}" ) - list(APPEND _IMPORT_CHECK_TARGETS assimp::assimp ) - list(APPEND _IMPORT_CHECK_FILES_FOR_assimp::assimp "${_IMPORT_PREFIX}/lib/${sharedLibraryName}" ) + list(APPEND _IMPORT_CHECK_TARGETS assimp::assimp ) + list(APPEND _IMPORT_CHECK_FILES_FOR_assimp::assimp "${_IMPORT_PREFIX}/lib/${sharedLibraryName}" ) + else() + set(staticLibraryName "libassimp${ASSIMP_LIBRARY_SUFFIX}@CMAKE_DEBUG_POSTFIX@@CMAKE_STATIC_LIBRARY_SUFFIX@") + set_target_properties(assimp::assimp PROPERTIES + IMPORTED_LOCATION_DEBUG "${_IMPORT_PREFIX}/lib/${staticLibraryName}" + ) + list(APPEND _IMPORT_CHECK_TARGETS assimp::assimp ) + list(APPEND _IMPORT_CHECK_FILES_FOR_assimp::assimp "${_IMPORT_PREFIX}/lib/${staticLibraryName}" ) + endif() endif() @@ -60,7 +91,11 @@ set( ASSIMP_CXX_FLAGS ) # dynamically linked library set( ASSIMP_LINK_FLAGS "" ) set( ASSIMP_LIBRARY_DIRS "${ASSIMP_ROOT_DIR}/@ASSIMP_LIB_INSTALL_DIR@") set( ASSIMP_INCLUDE_DIRS "${ASSIMP_ROOT_DIR}/@ASSIMP_INCLUDE_INSTALL_DIR@") -set( ASSIMP_LIBRARIES ${sharedLibraryName}) +if(ASSIMP_BUILD_SHARED_LIBS) + set( ASSIMP_LIBRARIES ${sharedLibraryName}) +else() + set( ASSIMP_LIBRARIES ${staticLibraryName}) +endif() # for compatibility with pkg-config set(ASSIMP_CFLAGS_OTHER "${ASSIMP_CXX_FLAGS}") @@ -75,4 +110,5 @@ MARK_AS_ADVANCED( ASSIMP_CFLAGS_OTHER ASSIMP_LDFLAGS_OTHER ASSIMP_LIBRARY_SUFFIX + ASSIMP_BUILD_SHARED_LIBS ) diff --git a/third_party/libassimp/assimpTargets-release.cmake.in b/third_party/libassimp/assimpTargets-release.cmake.in index 0b38e4e924..f3db8f12cd 100644 --- a/third_party/libassimp/assimpTargets-release.cmake.in +++ b/third_party/libassimp/assimpTargets-release.cmake.in @@ -5,59 +5,99 @@ # Commands may need to know the format version. set(CMAKE_IMPORT_FILE_VERSION 1) +set(ASSIMP_BUILD_SHARED_LIBS @BUILD_SHARED_LIBS@) + if(MSVC) - if( MSVC70 OR MSVC71 ) - set(MSVC_PREFIX "vc70") - elseif( MSVC80 ) - set(MSVC_PREFIX "vc80") - elseif( MSVC90 ) - set(MSVC_PREFIX "vc90") - elseif( MSVC10 ) - set(MSVC_PREFIX "vc100") - elseif( MSVC11 ) - set(MSVC_PREFIX "vc110") - elseif( MSVC12 ) - set(MSVC_PREFIX "vc120") - elseif( MSVC14 ) - set(MSVC_PREFIX "vc140") + if(MSVC_TOOLSET_VERSION) + set(MSVC_PREFIX "vc${MSVC_TOOLSET_VERSION}") else() - set(MSVC_PREFIX "vc150") + if( MSVC70 OR MSVC71 ) + set(MSVC_PREFIX "vc70") + elseif( MSVC80 ) + set(MSVC_PREFIX "vc80") + elseif( MSVC90 ) + set(MSVC_PREFIX "vc90") + elseif( MSVC10 ) + set(MSVC_PREFIX "vc100") + elseif( MSVC11 ) + set(MSVC_PREFIX "vc110") + elseif( MSVC12 ) + set(MSVC_PREFIX "vc120") + elseif( MSVC_VERSION LESS 1910) + set(MSVC_PREFIX "vc140") + elseif( MSVC_VERSION LESS 1920) + set(MSVC_PREFIX "vc141") + elseif( MSVC_VERSION LESS 1930) + set(MSVC_PREFIX "vc142") + else() + set(MSVC_PREFIX "vc150") + endif() endif() set(ASSIMP_LIBRARY_SUFFIX "@ASSIMP_LIBRARY_SUFFIX@-${MSVC_PREFIX}-mt" CACHE STRING "the suffix for the assimp windows library" ) - set(sharedLibraryName "assimp${ASSIMP_LIBRARY_SUFFIX}@CMAKE_SHARED_LIBRARY_SUFFIX@") - set(importLibraryName "assimp${ASSIMP_LIBRARY_SUFFIX}@CMAKE_IMPORT_LIBRARY_SUFFIX@") + if(ASSIMP_BUILD_SHARED_LIBS) + set(sharedLibraryName "assimp${ASSIMP_LIBRARY_SUFFIX}@CMAKE_SHARED_LIBRARY_SUFFIX@") + set(importLibraryName "assimp${ASSIMP_LIBRARY_SUFFIX}@CMAKE_IMPORT_LIBRARY_SUFFIX@") - # Import target "assimp::assimp" for configuration "Release" - set_property(TARGET assimp::assimp APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE) - set_target_properties(assimp::assimp PROPERTIES - IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/${importLibraryName}" - IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/bin/${sharedLibraryName}" + # Import target "assimp::assimp" for configuration "Release" + set_property(TARGET assimp::assimp APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE) + set_target_properties(assimp::assimp PROPERTIES + IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/${importLibraryName}" + IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/bin/${sharedLibraryName}" ) - list(APPEND _IMPORT_CHECK_TARGETS assimp::assimp ) - list(APPEND _IMPORT_CHECK_FILES_FOR_assimp::assimp "${_IMPORT_PREFIX}/lib/${importLibraryName}") - list(APPEND _IMPORT_CHECK_FILES_FOR_assimp::assimp "${_IMPORT_PREFIX}/bin/${sharedLibraryName}" ) + list(APPEND _IMPORT_CHECK_TARGETS assimp::assimp ) + list(APPEND _IMPORT_CHECK_FILES_FOR_assimp::assimp "${_IMPORT_PREFIX}/lib/${importLibraryName}") + list(APPEND _IMPORT_CHECK_FILES_FOR_assimp::assimp "${_IMPORT_PREFIX}/bin/${sharedLibraryName}" ) + else() + set(staticLibraryName "assimp${ASSIMP_LIBRARY_SUFFIX}@CMAKE_STATIC_LIBRARY_SUFFIX@") + + # Import target "assimp::assimp" for configuration "Release" + set_property(TARGET assimp::assimp APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE) + set_target_properties(assimp::assimp PROPERTIES + IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/${staticLibraryName}" + ) + list(APPEND _IMPORT_CHECK_TARGETS assimp::assimp ) + list(APPEND _IMPORT_CHECK_FILES_FOR_assimp::assimp "${_IMPORT_PREFIX}/lib/${staticLibraryName}") + endif() else() - set(ASSIMP_LIBRARY_SUFFIX "@ASSIMP_LIBRARY_SUFFIX@" CACHE STRING "the suffix for the openrave libraries" ) - set(sharedLibraryName "libassimp${ASSIMP_LIBRARY_SUFFIX}@CMAKE_SHARED_LIBRARY_SUFFIX@.@ASSIMP_VERSION_MAJOR@") - set_target_properties(assimp::assimp PROPERTIES - IMPORTED_SONAME_RELEASE "${sharedLibraryName}" - IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/${sharedLibraryName}" + set(ASSIMP_LIBRARY_SUFFIX "@ASSIMP_LIBRARY_SUFFIX@" CACHE STRING "the suffix for the assimp libraries" ) + if(ASSIMP_BUILD_SHARED_LIBS) + if(APPLE) + set(sharedLibraryName "libassimp${ASSIMP_LIBRARY_SUFFIX}.@ASSIMP_VERSION_MAJOR@@CMAKE_SHARED_LIBRARY_SUFFIX@") + else() + set(sharedLibraryName "libassimp${ASSIMP_LIBRARY_SUFFIX}@CMAKE_SHARED_LIBRARY_SUFFIX@.@ASSIMP_VERSION_MAJOR@") + endif() + set_target_properties(assimp::assimp PROPERTIES + IMPORTED_SONAME_RELEASE "${sharedLibraryName}" + IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/${sharedLibraryName}" ) - list(APPEND _IMPORT_CHECK_TARGETS assimp::assimp ) - list(APPEND _IMPORT_CHECK_FILES_FOR_assimp::assimp "${_IMPORT_PREFIX}/lib/${sharedLibraryName}" ) + list(APPEND _IMPORT_CHECK_TARGETS assimp::assimp ) + list(APPEND _IMPORT_CHECK_FILES_FOR_assimp::assimp "${_IMPORT_PREFIX}/lib/${sharedLibraryName}" ) + else() + set(staticLibraryName "libassimp${ASSIMP_LIBRARY_SUFFIX}@CMAKE_STATIC_LIBRARY_SUFFIX@") + set_target_properties(assimp::assimp PROPERTIES + IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/${staticLibraryName}" + ) + list(APPEND _IMPORT_CHECK_TARGETS assimp::assimp ) + list(APPEND _IMPORT_CHECK_FILES_FOR_assimp::assimp "${_IMPORT_PREFIX}/lib/${staticLibraryName}" ) + endif() endif() # Commands beyond this point should not need to know the version. set(CMAKE_IMPORT_FILE_VERSION) get_filename_component(ASSIMP_ROOT_DIR "@CMAKE_INSTALL_PREFIX@" REALPATH) + set( ASSIMP_CXX_FLAGS ) # dynamically linked library set( ASSIMP_LINK_FLAGS "" ) set( ASSIMP_LIBRARY_DIRS "${ASSIMP_ROOT_DIR}/@ASSIMP_LIB_INSTALL_DIR@") set( ASSIMP_INCLUDE_DIRS "${ASSIMP_ROOT_DIR}/@ASSIMP_INCLUDE_INSTALL_DIR@") -set( ASSIMP_LIBRARIES ${sharedLibraryName}) +if(ASSIMP_BUILD_SHARED_LIBS) + set( ASSIMP_LIBRARIES ${sharedLibraryName}) +else() + set( ASSIMP_LIBRARIES ${staticLibraryName}) +endif() # for compatibility with pkg-config set(ASSIMP_CFLAGS_OTHER "${ASSIMP_CXX_FLAGS}") @@ -72,4 +112,5 @@ MARK_AS_ADVANCED( ASSIMP_CFLAGS_OTHER ASSIMP_LDFLAGS_OTHER ASSIMP_LIBRARY_SUFFIX + ASSIMP_BUILD_SHARED_LIBS ) diff --git a/third_party/libassimp/assimpTargets.cmake.in b/third_party/libassimp/assimpTargets.cmake.in index 68e2c0dec1..ab1a8d2c7b 100644 --- a/third_party/libassimp/assimpTargets.cmake.in +++ b/third_party/libassimp/assimpTargets.cmake.in @@ -51,7 +51,11 @@ if(_IMPORT_PREFIX STREQUAL "/") endif() # Create imported target assimp::assimp -add_library(assimp::assimp SHARED IMPORTED) +if(@BUILD_SHARED_LIBS@) + add_library(assimp::assimp SHARED IMPORTED) +else() + add_library(assimp::assimp STATIC IMPORTED) +endif() set_target_properties(assimp::assimp PROPERTIES COMPATIBLE_INTERFACE_STRING "assimp_MAJOR_VERSION" diff --git a/third_party/libassimp/cmake/HunterGate.cmake b/third_party/libassimp/cmake/HunterGate.cmake new file mode 100644 index 0000000000..887557a584 --- /dev/null +++ b/third_party/libassimp/cmake/HunterGate.cmake @@ -0,0 +1,540 @@ +# Copyright (c) 2013-2018, Ruslan Baratov +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# 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 HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND 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. + +# This is a gate file to Hunter package manager. +# Include this file using `include` command and add package you need, example: +# +# cmake_minimum_required(VERSION 3.2) +# +# include("cmake/HunterGate.cmake") +# HunterGate( +# URL "https://github.com/path/to/hunter/archive.tar.gz" +# SHA1 "798501e983f14b28b10cda16afa4de69eee1da1d" +# ) +# +# project(MyProject) +# +# hunter_add_package(Foo) +# hunter_add_package(Boo COMPONENTS Bar Baz) +# +# Projects: +# * https://github.com/hunter-packages/gate/ +# * https://github.com/ruslo/hunter + +option(HUNTER_ENABLED "Enable Hunter package manager support" ON) + +if(HUNTER_ENABLED) + if(CMAKE_VERSION VERSION_LESS "3.2") + message( + FATAL_ERROR + "At least CMake version 3.2 required for Hunter dependency management." + " Update CMake or set HUNTER_ENABLED to OFF." + ) + endif() +endif() + +include(CMakeParseArguments) # cmake_parse_arguments + +option(HUNTER_STATUS_PRINT "Print working status" ON) +option(HUNTER_STATUS_DEBUG "Print a lot info" OFF) +option(HUNTER_TLS_VERIFY "Enable/disable TLS certificate checking on downloads" ON) + +set(HUNTER_WIKI "https://github.com/ruslo/hunter/wiki") + +function(hunter_gate_status_print) + if(HUNTER_STATUS_PRINT OR HUNTER_STATUS_DEBUG) + foreach(print_message ${ARGV}) + message(STATUS "[hunter] ${print_message}") + endforeach() + endif() +endfunction() + +function(hunter_gate_status_debug) + if(HUNTER_STATUS_DEBUG) + foreach(print_message ${ARGV}) + string(TIMESTAMP timestamp) + message(STATUS "[hunter *** DEBUG *** ${timestamp}] ${print_message}") + endforeach() + endif() +endfunction() + +function(hunter_gate_wiki wiki_page) + message("------------------------------ WIKI -------------------------------") + message(" ${HUNTER_WIKI}/${wiki_page}") + message("-------------------------------------------------------------------") + message("") + message(FATAL_ERROR "") +endfunction() + +function(hunter_gate_internal_error) + message("") + foreach(print_message ${ARGV}) + message("[hunter ** INTERNAL **] ${print_message}") + endforeach() + message("[hunter ** INTERNAL **] [Directory:${CMAKE_CURRENT_LIST_DIR}]") + message("") + hunter_gate_wiki("error.internal") +endfunction() + +function(hunter_gate_fatal_error) + cmake_parse_arguments(hunter "" "WIKI" "" "${ARGV}") + string(COMPARE EQUAL "${hunter_WIKI}" "" have_no_wiki) + if(have_no_wiki) + hunter_gate_internal_error("Expected wiki") + endif() + message("") + foreach(x ${hunter_UNPARSED_ARGUMENTS}) + message("[hunter ** FATAL ERROR **] ${x}") + endforeach() + message("[hunter ** FATAL ERROR **] [Directory:${CMAKE_CURRENT_LIST_DIR}]") + message("") + hunter_gate_wiki("${hunter_WIKI}") +endfunction() + +function(hunter_gate_user_error) + hunter_gate_fatal_error(${ARGV} WIKI "error.incorrect.input.data") +endfunction() + +function(hunter_gate_self root version sha1 result) + string(COMPARE EQUAL "${root}" "" is_bad) + if(is_bad) + hunter_gate_internal_error("root is empty") + endif() + + string(COMPARE EQUAL "${version}" "" is_bad) + if(is_bad) + hunter_gate_internal_error("version is empty") + endif() + + string(COMPARE EQUAL "${sha1}" "" is_bad) + if(is_bad) + hunter_gate_internal_error("sha1 is empty") + endif() + + string(SUBSTRING "${sha1}" 0 7 archive_id) + + if(EXISTS "${root}/cmake/Hunter") + set(hunter_self "${root}") + else() + set( + hunter_self + "${root}/_Base/Download/Hunter/${version}/${archive_id}/Unpacked" + ) + endif() + + set("${result}" "${hunter_self}" PARENT_SCOPE) +endfunction() + +# Set HUNTER_GATE_ROOT cmake variable to suitable value. +function(hunter_gate_detect_root) + # Check CMake variable + string(COMPARE NOTEQUAL "${HUNTER_ROOT}" "" not_empty) + if(not_empty) + set(HUNTER_GATE_ROOT "${HUNTER_ROOT}" PARENT_SCOPE) + hunter_gate_status_debug("HUNTER_ROOT detected by cmake variable") + return() + endif() + + # Check environment variable + string(COMPARE NOTEQUAL "$ENV{HUNTER_ROOT}" "" not_empty) + if(not_empty) + set(HUNTER_GATE_ROOT "$ENV{HUNTER_ROOT}" PARENT_SCOPE) + hunter_gate_status_debug("HUNTER_ROOT detected by environment variable") + return() + endif() + + # Check HOME environment variable + string(COMPARE NOTEQUAL "$ENV{HOME}" "" result) + if(result) + set(HUNTER_GATE_ROOT "$ENV{HOME}/.hunter" PARENT_SCOPE) + hunter_gate_status_debug("HUNTER_ROOT set using HOME environment variable") + return() + endif() + + # Check SYSTEMDRIVE and USERPROFILE environment variable (windows only) + if(WIN32) + string(COMPARE NOTEQUAL "$ENV{SYSTEMDRIVE}" "" result) + if(result) + set(HUNTER_GATE_ROOT "$ENV{SYSTEMDRIVE}/.hunter" PARENT_SCOPE) + hunter_gate_status_debug( + "HUNTER_ROOT set using SYSTEMDRIVE environment variable" + ) + return() + endif() + + string(COMPARE NOTEQUAL "$ENV{USERPROFILE}" "" result) + if(result) + set(HUNTER_GATE_ROOT "$ENV{USERPROFILE}/.hunter" PARENT_SCOPE) + hunter_gate_status_debug( + "HUNTER_ROOT set using USERPROFILE environment variable" + ) + return() + endif() + endif() + + hunter_gate_fatal_error( + "Can't detect HUNTER_ROOT" + WIKI "error.detect.hunter.root" + ) +endfunction() + +function(hunter_gate_download dir) + string( + COMPARE + NOTEQUAL + "$ENV{HUNTER_DISABLE_AUTOINSTALL}" + "" + disable_autoinstall + ) + if(disable_autoinstall AND NOT HUNTER_RUN_INSTALL) + hunter_gate_fatal_error( + "Hunter not found in '${dir}'" + "Set HUNTER_RUN_INSTALL=ON to auto-install it from '${HUNTER_GATE_URL}'" + "Settings:" + " HUNTER_ROOT: ${HUNTER_GATE_ROOT}" + " HUNTER_SHA1: ${HUNTER_GATE_SHA1}" + WIKI "error.run.install" + ) + endif() + string(COMPARE EQUAL "${dir}" "" is_bad) + if(is_bad) + hunter_gate_internal_error("Empty 'dir' argument") + endif() + + string(COMPARE EQUAL "${HUNTER_GATE_SHA1}" "" is_bad) + if(is_bad) + hunter_gate_internal_error("HUNTER_GATE_SHA1 empty") + endif() + + string(COMPARE EQUAL "${HUNTER_GATE_URL}" "" is_bad) + if(is_bad) + hunter_gate_internal_error("HUNTER_GATE_URL empty") + endif() + + set(done_location "${dir}/DONE") + set(sha1_location "${dir}/SHA1") + + set(build_dir "${dir}/Build") + set(cmakelists "${dir}/CMakeLists.txt") + + hunter_gate_status_debug("Locking directory: ${dir}") + file(LOCK "${dir}" DIRECTORY GUARD FUNCTION) + hunter_gate_status_debug("Lock done") + + if(EXISTS "${done_location}") + # while waiting for lock other instance can do all the job + hunter_gate_status_debug("File '${done_location}' found, skip install") + return() + endif() + + file(REMOVE_RECURSE "${build_dir}") + file(REMOVE_RECURSE "${cmakelists}") + + file(MAKE_DIRECTORY "${build_dir}") # check directory permissions + + # Disabling languages speeds up a little bit, reduces noise in the output + # and avoids path too long windows error + file( + WRITE + "${cmakelists}" + "cmake_minimum_required(VERSION 3.2)\n" + "project(HunterDownload LANGUAGES NONE)\n" + "include(ExternalProject)\n" + "ExternalProject_Add(\n" + " Hunter\n" + " URL\n" + " \"${HUNTER_GATE_URL}\"\n" + " URL_HASH\n" + " SHA1=${HUNTER_GATE_SHA1}\n" + " DOWNLOAD_DIR\n" + " \"${dir}\"\n" + " TLS_VERIFY\n" + " ${HUNTER_TLS_VERIFY}\n" + " SOURCE_DIR\n" + " \"${dir}/Unpacked\"\n" + " CONFIGURE_COMMAND\n" + " \"\"\n" + " BUILD_COMMAND\n" + " \"\"\n" + " INSTALL_COMMAND\n" + " \"\"\n" + ")\n" + ) + + if(HUNTER_STATUS_DEBUG) + set(logging_params "") + else() + set(logging_params OUTPUT_QUIET) + endif() + + hunter_gate_status_debug("Run generate") + + # Need to add toolchain file too. + # Otherwise on Visual Studio + MDD this will fail with error: + # "Could not find an appropriate version of the Windows 10 SDK installed on this machine" + if(EXISTS "${CMAKE_TOOLCHAIN_FILE}") + get_filename_component(absolute_CMAKE_TOOLCHAIN_FILE "${CMAKE_TOOLCHAIN_FILE}" ABSOLUTE) + set(toolchain_arg "-DCMAKE_TOOLCHAIN_FILE=${absolute_CMAKE_TOOLCHAIN_FILE}") + else() + # 'toolchain_arg' can't be empty + set(toolchain_arg "-DCMAKE_TOOLCHAIN_FILE=") + endif() + + string(COMPARE EQUAL "${CMAKE_MAKE_PROGRAM}" "" no_make) + if(no_make) + set(make_arg "") + else() + # Test case: remove Ninja from PATH but set it via CMAKE_MAKE_PROGRAM + set(make_arg "-DCMAKE_MAKE_PROGRAM=${CMAKE_MAKE_PROGRAM}") + endif() + + execute_process( + COMMAND + "${CMAKE_COMMAND}" + "-H${dir}" + "-B${build_dir}" + "-G${CMAKE_GENERATOR}" + "${toolchain_arg}" + ${make_arg} + WORKING_DIRECTORY "${dir}" + RESULT_VARIABLE download_result + ${logging_params} + ) + + if(NOT download_result EQUAL 0) + hunter_gate_internal_error( + "Configure project failed." + "To reproduce the error run: ${CMAKE_COMMAND} -H${dir} -B${build_dir} -G${CMAKE_GENERATOR} ${toolchain_arg} ${make_arg}" + "In directory ${dir}" + ) + endif() + + hunter_gate_status_print( + "Initializing Hunter workspace (${HUNTER_GATE_SHA1})" + " ${HUNTER_GATE_URL}" + " -> ${dir}" + ) + execute_process( + COMMAND "${CMAKE_COMMAND}" --build "${build_dir}" + WORKING_DIRECTORY "${dir}" + RESULT_VARIABLE download_result + ${logging_params} + ) + + if(NOT download_result EQUAL 0) + hunter_gate_internal_error("Build project failed") + endif() + + file(REMOVE_RECURSE "${build_dir}") + file(REMOVE_RECURSE "${cmakelists}") + + file(WRITE "${sha1_location}" "${HUNTER_GATE_SHA1}") + file(WRITE "${done_location}" "DONE") + + hunter_gate_status_debug("Finished") +endfunction() + +# Must be a macro so master file 'cmake/Hunter' can +# apply all variables easily just by 'include' command +# (otherwise PARENT_SCOPE magic needed) +macro(HunterGate) + if(HUNTER_GATE_DONE) + # variable HUNTER_GATE_DONE set explicitly for external project + # (see `hunter_download`) + set_property(GLOBAL PROPERTY HUNTER_GATE_DONE YES) + endif() + + # First HunterGate command will init Hunter, others will be ignored + get_property(_hunter_gate_done GLOBAL PROPERTY HUNTER_GATE_DONE SET) + + if(NOT HUNTER_ENABLED) + # Empty function to avoid error "unknown function" + function(hunter_add_package) + endfunction() + + set( + _hunter_gate_disabled_mode_dir + "${CMAKE_CURRENT_LIST_DIR}/cmake/Hunter/disabled-mode" + ) + if(EXISTS "${_hunter_gate_disabled_mode_dir}") + hunter_gate_status_debug( + "Adding \"disabled-mode\" modules: ${_hunter_gate_disabled_mode_dir}" + ) + list(APPEND CMAKE_PREFIX_PATH "${_hunter_gate_disabled_mode_dir}") + endif() + elseif(_hunter_gate_done) + hunter_gate_status_debug("Secondary HunterGate (use old settings)") + hunter_gate_self( + "${HUNTER_CACHED_ROOT}" + "${HUNTER_VERSION}" + "${HUNTER_SHA1}" + _hunter_self + ) + include("${_hunter_self}/cmake/Hunter") + else() + set(HUNTER_GATE_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}") + + string(COMPARE NOTEQUAL "${PROJECT_NAME}" "" _have_project_name) + if(_have_project_name) + hunter_gate_fatal_error( + "Please set HunterGate *before* 'project' command. " + "Detected project: ${PROJECT_NAME}" + WIKI "error.huntergate.before.project" + ) + endif() + + cmake_parse_arguments( + HUNTER_GATE "LOCAL" "URL;SHA1;GLOBAL;FILEPATH" "" ${ARGV} + ) + + string(COMPARE EQUAL "${HUNTER_GATE_SHA1}" "" _empty_sha1) + string(COMPARE EQUAL "${HUNTER_GATE_URL}" "" _empty_url) + string( + COMPARE + NOTEQUAL + "${HUNTER_GATE_UNPARSED_ARGUMENTS}" + "" + _have_unparsed + ) + string(COMPARE NOTEQUAL "${HUNTER_GATE_GLOBAL}" "" _have_global) + string(COMPARE NOTEQUAL "${HUNTER_GATE_FILEPATH}" "" _have_filepath) + + if(_have_unparsed) + hunter_gate_user_error( + "HunterGate unparsed arguments: ${HUNTER_GATE_UNPARSED_ARGUMENTS}" + ) + endif() + if(_empty_sha1) + hunter_gate_user_error("SHA1 suboption of HunterGate is mandatory") + endif() + if(_empty_url) + hunter_gate_user_error("URL suboption of HunterGate is mandatory") + endif() + if(_have_global) + if(HUNTER_GATE_LOCAL) + hunter_gate_user_error("Unexpected LOCAL (already has GLOBAL)") + endif() + if(_have_filepath) + hunter_gate_user_error("Unexpected FILEPATH (already has GLOBAL)") + endif() + endif() + if(HUNTER_GATE_LOCAL) + if(_have_global) + hunter_gate_user_error("Unexpected GLOBAL (already has LOCAL)") + endif() + if(_have_filepath) + hunter_gate_user_error("Unexpected FILEPATH (already has LOCAL)") + endif() + endif() + if(_have_filepath) + if(_have_global) + hunter_gate_user_error("Unexpected GLOBAL (already has FILEPATH)") + endif() + if(HUNTER_GATE_LOCAL) + hunter_gate_user_error("Unexpected LOCAL (already has FILEPATH)") + endif() + endif() + + hunter_gate_detect_root() # set HUNTER_GATE_ROOT + + # Beautify path, fix probable problems with windows path slashes + get_filename_component( + HUNTER_GATE_ROOT "${HUNTER_GATE_ROOT}" ABSOLUTE + ) + hunter_gate_status_debug("HUNTER_ROOT: ${HUNTER_GATE_ROOT}") + if(NOT HUNTER_ALLOW_SPACES_IN_PATH) + string(FIND "${HUNTER_GATE_ROOT}" " " _contain_spaces) + if(NOT _contain_spaces EQUAL -1) + hunter_gate_fatal_error( + "HUNTER_ROOT (${HUNTER_GATE_ROOT}) contains spaces." + "Set HUNTER_ALLOW_SPACES_IN_PATH=ON to skip this error" + "(Use at your own risk!)" + WIKI "error.spaces.in.hunter.root" + ) + endif() + endif() + + string( + REGEX + MATCH + "[0-9]+\\.[0-9]+\\.[0-9]+[-_a-z0-9]*" + HUNTER_GATE_VERSION + "${HUNTER_GATE_URL}" + ) + string(COMPARE EQUAL "${HUNTER_GATE_VERSION}" "" _is_empty) + if(_is_empty) + set(HUNTER_GATE_VERSION "unknown") + endif() + + hunter_gate_self( + "${HUNTER_GATE_ROOT}" + "${HUNTER_GATE_VERSION}" + "${HUNTER_GATE_SHA1}" + _hunter_self + ) + + set(_master_location "${_hunter_self}/cmake/Hunter") + if(EXISTS "${HUNTER_GATE_ROOT}/cmake/Hunter") + # Hunter downloaded manually (e.g. by 'git clone') + set(_unused "xxxxxxxxxx") + set(HUNTER_GATE_SHA1 "${_unused}") + set(HUNTER_GATE_VERSION "${_unused}") + else() + get_filename_component(_archive_id_location "${_hunter_self}/.." ABSOLUTE) + set(_done_location "${_archive_id_location}/DONE") + set(_sha1_location "${_archive_id_location}/SHA1") + + # Check Hunter already downloaded by HunterGate + if(NOT EXISTS "${_done_location}") + hunter_gate_download("${_archive_id_location}") + endif() + + if(NOT EXISTS "${_done_location}") + hunter_gate_internal_error("hunter_gate_download failed") + endif() + + if(NOT EXISTS "${_sha1_location}") + hunter_gate_internal_error("${_sha1_location} not found") + endif() + file(READ "${_sha1_location}" _sha1_value) + string(COMPARE EQUAL "${_sha1_value}" "${HUNTER_GATE_SHA1}" _is_equal) + if(NOT _is_equal) + hunter_gate_internal_error( + "Short SHA1 collision:" + " ${_sha1_value} (from ${_sha1_location})" + " ${HUNTER_GATE_SHA1} (HunterGate)" + ) + endif() + if(NOT EXISTS "${_master_location}") + hunter_gate_user_error( + "Master file not found:" + " ${_master_location}" + "try to update Hunter/HunterGate" + ) + endif() + endif() + include("${_master_location}") + set_property(GLOBAL PROPERTY HUNTER_GATE_DONE YES) + endif() +endmacro() diff --git a/third_party/libassimp/cmake/assimp-hunter-config.cmake.in b/third_party/libassimp/cmake/assimp-hunter-config.cmake.in new file mode 100644 index 0000000000..34762ac54b --- /dev/null +++ b/third_party/libassimp/cmake/assimp-hunter-config.cmake.in @@ -0,0 +1,14 @@ +@PACKAGE_INIT@ + +find_package(RapidJSON CONFIG REQUIRED) +find_package(ZLIB CONFIG REQUIRED) +find_package(utf8 CONFIG REQUIRED) +find_package(irrXML CONFIG REQUIRED) +find_package(minizip CONFIG REQUIRED) +find_package(openddlparser CONFIG REQUIRED) +find_package(poly2tri CONFIG REQUIRED) +find_package(polyclipping CONFIG REQUIRED) +find_package(zip CONFIG REQUIRED) + +include("${CMAKE_CURRENT_LIST_DIR}/@TARGETS_EXPORT_NAME@.cmake") +check_required_components("@PROJECT_NAME@") diff --git a/third_party/libassimp/code/3DSConverter.cpp b/third_party/libassimp/code/3DS/3DSConverter.cpp similarity index 99% rename from third_party/libassimp/code/3DSConverter.cpp rename to third_party/libassimp/code/3DS/3DSConverter.cpp index 7ec79ba640..2176b75fc2 100644 --- a/third_party/libassimp/code/3DSConverter.cpp +++ b/third_party/libassimp/code/3DS/3DSConverter.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -48,7 +48,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // internal headers #include "3DSLoader.h" -#include "TargetAnimation.h" +#include "Common/TargetAnimation.h" #include #include #include diff --git a/third_party/libassimp/code/3DSExporter.cpp b/third_party/libassimp/code/3DS/3DSExporter.cpp similarity index 99% rename from third_party/libassimp/code/3DSExporter.cpp rename to third_party/libassimp/code/3DS/3DSExporter.cpp index 53976b16fe..1117a52ef2 100644 --- a/third_party/libassimp/code/3DSExporter.cpp +++ b/third_party/libassimp/code/3DS/3DSExporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -43,15 +43,17 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_EXPORT #ifndef ASSIMP_BUILD_NO_3DS_EXPORTER -#include "3DSExporter.h" -#include "3DSLoader.h" -#include "3DSHelper.h" +#include "3DS/3DSExporter.h" +#include "3DS/3DSLoader.h" +#include "3DS/3DSHelper.h" +#include "PostProcessing/SplitLargeMeshes.h" + #include -#include "SplitLargeMeshes.h" #include #include #include #include + #include using namespace Assimp; diff --git a/third_party/libassimp/code/3DSExporter.h b/third_party/libassimp/code/3DS/3DSExporter.h similarity index 98% rename from third_party/libassimp/code/3DSExporter.h rename to third_party/libassimp/code/3DS/3DSExporter.h index 5db58a4cb5..035b562cf9 100644 --- a/third_party/libassimp/code/3DSExporter.h +++ b/third_party/libassimp/code/3DS/3DSExporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/3DSHelper.h b/third_party/libassimp/code/3DS/3DSHelper.h similarity index 99% rename from third_party/libassimp/code/3DSHelper.h rename to third_party/libassimp/code/3DS/3DSHelper.h index d67a7c14ce..8eb4cd97ce 100644 --- a/third_party/libassimp/code/3DSHelper.h +++ b/third_party/libassimp/code/3DS/3DSHelper.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/3DSLoader.cpp b/third_party/libassimp/code/3DS/3DSLoader.cpp similarity index 99% rename from third_party/libassimp/code/3DSLoader.cpp rename to third_party/libassimp/code/3DS/3DSLoader.cpp index 34066e44b0..96b80c962c 100644 --- a/third_party/libassimp/code/3DSLoader.cpp +++ b/third_party/libassimp/code/3DS/3DSLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -249,13 +249,14 @@ void Discreet3DSImporter::ApplyMasterScale(aiScene* pScene) // Reads a new chunk from the file void Discreet3DSImporter::ReadChunk(Discreet3DS::Chunk* pcOut) { - ai_assert(pcOut != NULL); + ai_assert(pcOut != nullptr); pcOut->Flag = stream->GetI2(); pcOut->Size = stream->GetI4(); - if (pcOut->Size - sizeof(Discreet3DS::Chunk) > stream->GetRemainingSize()) + if (pcOut->Size - sizeof(Discreet3DS::Chunk) > stream->GetRemainingSize()) { throw DeadlyImportError("Chunk is too large"); + } if (pcOut->Size - sizeof(Discreet3DS::Chunk) > stream->GetRemainingSizeToLimit()) { ASSIMP_LOG_ERROR("3DS: Chunk overflow"); @@ -1343,15 +1344,16 @@ void Discreet3DSImporter::ParseTextureChunk(D3DS::Texture* pcOut) // ------------------------------------------------------------------------------------------------ // Read a percentage chunk -ai_real Discreet3DSImporter::ParsePercentageChunk() -{ +ai_real Discreet3DSImporter::ParsePercentageChunk() { Discreet3DS::Chunk chunk; ReadChunk(&chunk); - if (Discreet3DS::CHUNK_PERCENTF == chunk.Flag) - return stream->GetF4(); - else if (Discreet3DS::CHUNK_PERCENTW == chunk.Flag) + if (Discreet3DS::CHUNK_PERCENTF == chunk.Flag) { + return stream->GetF4() * ai_real(100) / ai_real(0xFFFF); + } else if (Discreet3DS::CHUNK_PERCENTW == chunk.Flag) { return (ai_real)((uint16_t)stream->GetI2()) / (ai_real)0xFFFF; + } + return get_qnan(); } diff --git a/third_party/libassimp/code/3DSLoader.h b/third_party/libassimp/code/3DS/3DSLoader.h similarity index 99% rename from third_party/libassimp/code/3DSLoader.h rename to third_party/libassimp/code/3DS/3DSLoader.h index eb311a81b7..f57e6a8e39 100644 --- a/third_party/libassimp/code/3DSLoader.h +++ b/third_party/libassimp/code/3DS/3DSLoader.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/3MFXmlTags.h b/third_party/libassimp/code/3MF/3MFXmlTags.h similarity index 99% rename from third_party/libassimp/code/3MFXmlTags.h rename to third_party/libassimp/code/3MF/3MFXmlTags.h index e869c33c1c..ea6aeede03 100644 --- a/third_party/libassimp/code/3MFXmlTags.h +++ b/third_party/libassimp/code/3MF/3MFXmlTags.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/D3MFExporter.cpp b/third_party/libassimp/code/3MF/D3MFExporter.cpp similarity index 98% rename from third_party/libassimp/code/D3MFExporter.cpp rename to third_party/libassimp/code/3MF/D3MFExporter.cpp index 99e2ff3f57..1f388ad3ec 100644 --- a/third_party/libassimp/code/D3MFExporter.cpp +++ b/third_party/libassimp/code/3MF/D3MFExporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -55,7 +55,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "3MFXmlTags.h" #include "D3MFOpcPackage.h" -#include +#ifdef ASSIMP_USE_HUNTER +# include +#else +# include +#endif namespace Assimp { diff --git a/third_party/libassimp/code/D3MFExporter.h b/third_party/libassimp/code/3MF/D3MFExporter.h similarity index 98% rename from third_party/libassimp/code/D3MFExporter.h rename to third_party/libassimp/code/3MF/D3MFExporter.h index 110862b99d..e821202478 100644 --- a/third_party/libassimp/code/D3MFExporter.h +++ b/third_party/libassimp/code/3MF/D3MFExporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/D3MFImporter.cpp b/third_party/libassimp/code/3MF/D3MFImporter.cpp similarity index 99% rename from third_party/libassimp/code/D3MFImporter.cpp rename to third_party/libassimp/code/3MF/D3MFImporter.cpp index de57081491..682de684a3 100644 --- a/third_party/libassimp/code/D3MFImporter.cpp +++ b/third_party/libassimp/code/3MF/D3MFImporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -50,6 +50,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include +#include #include #include @@ -58,7 +59,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include "D3MFOpcPackage.h" -#include #include #include "3MFXmlTags.h" #include @@ -449,7 +449,7 @@ bool D3MFImporter::CanRead(const std::string &filename, IOSystem *pIOHandler, bo if ( nullptr == pIOHandler ) { return false; } - if ( !D3MF::D3MFOpcPackage::isZipArchive( pIOHandler, filename ) ) { + if ( !ZipArchiveIOSystem::isZipArchive( pIOHandler, filename ) ) { return false; } D3MF::D3MFOpcPackage opcPackage( pIOHandler, filename ); diff --git a/third_party/libassimp/code/D3MFImporter.h b/third_party/libassimp/code/3MF/D3MFImporter.h similarity index 98% rename from third_party/libassimp/code/D3MFImporter.h rename to third_party/libassimp/code/3MF/D3MFImporter.h index 701d056e29..3dbdf07bf6 100644 --- a/third_party/libassimp/code/D3MFImporter.h +++ b/third_party/libassimp/code/3MF/D3MFImporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/3MF/D3MFOpcPackage.cpp b/third_party/libassimp/code/3MF/D3MFOpcPackage.cpp new file mode 100644 index 0000000000..873ba8ee81 --- /dev/null +++ b/third_party/libassimp/code/3MF/D3MFOpcPackage.cpp @@ -0,0 +1,207 @@ +/* +Open Asset Import Library (assimp) +---------------------------------------------------------------------- + +Copyright (c) 2006-2019, 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. + +---------------------------------------------------------------------- +*/ + +#ifndef ASSIMP_BUILD_NO_3MF_IMPORTER + +#include "D3MFOpcPackage.h" +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include "3MFXmlTags.h" + +namespace Assimp { + +namespace D3MF { +// ------------------------------------------------------------------------------------------------ + +typedef std::shared_ptr OpcPackageRelationshipPtr; + +class OpcPackageRelationshipReader { +public: + OpcPackageRelationshipReader(XmlReader* xmlReader) { + while(xmlReader->read()) { + if(xmlReader->getNodeType() == irr::io::EXN_ELEMENT && + xmlReader->getNodeName() == XmlTag::RELS_RELATIONSHIP_CONTAINER) + { + ParseRootNode(xmlReader); + } + } + } + + void ParseRootNode(XmlReader* xmlReader) + { + ParseAttributes(xmlReader); + + while(xmlReader->read()) + { + if(xmlReader->getNodeType() == irr::io::EXN_ELEMENT && + xmlReader->getNodeName() == XmlTag::RELS_RELATIONSHIP_NODE) + { + ParseChildNode(xmlReader); + } + } + } + + void ParseAttributes(XmlReader*) { + // empty + } + + bool validateRels( OpcPackageRelationshipPtr &relPtr ) { + if ( relPtr->id.empty() || relPtr->type.empty() || relPtr->target.empty() ) { + return false; + } + return true; + } + + void ParseChildNode(XmlReader* xmlReader) { + OpcPackageRelationshipPtr relPtr(new OpcPackageRelationship()); + + relPtr->id = xmlReader->getAttributeValueSafe(XmlTag::RELS_ATTRIB_ID.c_str()); + relPtr->type = xmlReader->getAttributeValueSafe(XmlTag::RELS_ATTRIB_TYPE.c_str()); + relPtr->target = xmlReader->getAttributeValueSafe(XmlTag::RELS_ATTRIB_TARGET.c_str()); + if ( validateRels( relPtr ) ) { + m_relationShips.push_back( relPtr ); + } + } + + std::vector m_relationShips; +}; + +// ------------------------------------------------------------------------------------------------ +D3MFOpcPackage::D3MFOpcPackage(IOSystem* pIOHandler, const std::string& rFile) +: mRootStream(nullptr) +, mZipArchive() { + mZipArchive.reset( new ZipArchiveIOSystem( pIOHandler, rFile ) ); + if(!mZipArchive->isOpen()) { + throw DeadlyImportError("Failed to open file " + rFile+ "."); + } + + std::vector fileList; + mZipArchive->getFileList(fileList); + + for (auto& file: fileList) { + if(file == D3MF::XmlTag::ROOT_RELATIONSHIPS_ARCHIVE) { + //PkgRelationshipReader pkgRelReader(file, archive); + ai_assert(mZipArchive->Exists(file.c_str())); + + IOStream *fileStream = mZipArchive->Open(file.c_str()); + + ai_assert(fileStream != nullptr); + + std::string rootFile = ReadPackageRootRelationship(fileStream); + if ( rootFile.size() > 0 && rootFile[ 0 ] == '/' ) { + rootFile = rootFile.substr( 1 ); + if ( rootFile[ 0 ] == '/' ) { + // deal with zip-bug + rootFile = rootFile.substr( 1 ); + } + } + + ASSIMP_LOG_DEBUG(rootFile); + + mZipArchive->Close(fileStream); + + mRootStream = mZipArchive->Open(rootFile.c_str()); + ai_assert( mRootStream != nullptr ); + if ( nullptr == mRootStream ) { + throw DeadlyExportError( "Cannot open root-file in archive : " + rootFile ); + } + + } else if( file == D3MF::XmlTag::CONTENT_TYPES_ARCHIVE) { + ASSIMP_LOG_WARN_F("Ignored file of unsupported type CONTENT_TYPES_ARCHIVES",file); + } else { + ASSIMP_LOG_WARN_F("Ignored file of unknown type: ",file); + } + + } +} + +D3MFOpcPackage::~D3MFOpcPackage() { + mZipArchive->Close(mRootStream); +} + +IOStream* D3MFOpcPackage::RootStream() const { + return mRootStream; +} + +static const std::string ModelRef = "3D/3dmodel.model"; + +bool D3MFOpcPackage::validate() { + if ( nullptr == mRootStream || nullptr == mZipArchive ) { + return false; + } + + return mZipArchive->Exists( ModelRef.c_str() ); +} + +std::string D3MFOpcPackage::ReadPackageRootRelationship(IOStream* stream) { + std::unique_ptr xmlStream(new CIrrXML_IOStreamReader(stream)); + std::unique_ptr xml(irr::io::createIrrXMLReader(xmlStream.get())); + + OpcPackageRelationshipReader reader(xml.get()); + + auto itr = std::find_if(reader.m_relationShips.begin(), reader.m_relationShips.end(), [](const OpcPackageRelationshipPtr& rel){ + return rel->type == XmlTag::PACKAGE_START_PART_RELATIONSHIP_TYPE; + }); + + if ( itr == reader.m_relationShips.end() ) { + throw DeadlyImportError( "Cannot find " + XmlTag::PACKAGE_START_PART_RELATIONSHIP_TYPE ); + } + + return (*itr)->target; +} + +} // Namespace D3MF +} // Namespace Assimp + +#endif //ASSIMP_BUILD_NO_3MF_IMPORTER diff --git a/third_party/libassimp/code/D3MFOpcPackage.h b/third_party/libassimp/code/3MF/D3MFOpcPackage.h similarity index 92% rename from third_party/libassimp/code/D3MFOpcPackage.h rename to third_party/libassimp/code/3MF/D3MFOpcPackage.h index 6d7b3d478c..87d1721164 100644 --- a/third_party/libassimp/code/D3MFOpcPackage.h +++ b/third_party/libassimp/code/3MF/D3MFOpcPackage.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -49,6 +49,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include namespace Assimp { + class ZipArchiveIOSystem; + namespace D3MF { using XmlReader = irr::io::IrrXMLReader ; @@ -60,22 +62,19 @@ struct OpcPackageRelationship { std::string target; }; -class D3MFZipArchive; - class D3MFOpcPackage { public: D3MFOpcPackage( IOSystem* pIOHandler, const std::string& rFile ); ~D3MFOpcPackage(); IOStream* RootStream() const; bool validate(); - static bool isZipArchive( IOSystem* pIOHandler, const std::string& rFile ); protected: std::string ReadPackageRootRelationship(IOStream* stream); private: IOStream* mRootStream; - std::unique_ptr mZipArchive; + std::unique_ptr mZipArchive; }; } // Namespace D3MF diff --git a/third_party/libassimp/code/ACLoader.cpp b/third_party/libassimp/code/AC/ACLoader.cpp similarity index 99% rename from third_party/libassimp/code/ACLoader.cpp rename to third_party/libassimp/code/AC/ACLoader.cpp index 7b8afbe9b8..d4c4bd1a69 100644 --- a/third_party/libassimp/code/ACLoader.cpp +++ b/third_party/libassimp/code/AC/ACLoader.cpp @@ -4,7 +4,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -53,7 +53,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include -#include "Importer.h" +#include "Common/Importer.h" #include #include #include diff --git a/third_party/libassimp/code/ACLoader.h b/third_party/libassimp/code/AC/ACLoader.h similarity index 99% rename from third_party/libassimp/code/ACLoader.h rename to third_party/libassimp/code/AC/ACLoader.h index 86af9afb69..cab2c3ae54 100644 --- a/third_party/libassimp/code/ACLoader.h +++ b/third_party/libassimp/code/AC/ACLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/AMFImporter.cpp b/third_party/libassimp/code/AMF/AMFImporter.cpp similarity index 99% rename from third_party/libassimp/code/AMFImporter.cpp rename to third_party/libassimp/code/AMF/AMFImporter.cpp index e5b41b3ad5..dedb6dcddc 100644 --- a/third_party/libassimp/code/AMFImporter.cpp +++ b/third_party/libassimp/code/AMF/AMFImporter.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -83,7 +83,7 @@ void AMFImporter::Clear() mMaterial_Converted.clear(); mTexture_Converted.clear(); // Delete all elements - if(mNodeElement_List.size()) + if(!mNodeElement_List.empty()) { for(CAMFImporter_NodeElement* ne: mNodeElement_List) { delete ne; } diff --git a/third_party/libassimp/code/AMFImporter.hpp b/third_party/libassimp/code/AMF/AMFImporter.hpp similarity index 99% rename from third_party/libassimp/code/AMFImporter.hpp rename to third_party/libassimp/code/AMF/AMFImporter.hpp index b7e58362c2..2b8086a06f 100644 --- a/third_party/libassimp/code/AMFImporter.hpp +++ b/third_party/libassimp/code/AMF/AMFImporter.hpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/AMFImporter_Geometry.cpp b/third_party/libassimp/code/AMF/AMFImporter_Geometry.cpp similarity index 99% rename from third_party/libassimp/code/AMFImporter_Geometry.cpp rename to third_party/libassimp/code/AMF/AMFImporter_Geometry.cpp index d4d648fbd7..f1538e3fbd 100644 --- a/third_party/libassimp/code/AMFImporter_Geometry.cpp +++ b/third_party/libassimp/code/AMF/AMFImporter_Geometry.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/AMFImporter_Macro.hpp b/third_party/libassimp/code/AMF/AMFImporter_Macro.hpp similarity index 99% rename from third_party/libassimp/code/AMFImporter_Macro.hpp rename to third_party/libassimp/code/AMF/AMFImporter_Macro.hpp index ea8c178508..f60c5fbbb4 100644 --- a/third_party/libassimp/code/AMFImporter_Macro.hpp +++ b/third_party/libassimp/code/AMF/AMFImporter_Macro.hpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/AMFImporter_Material.cpp b/third_party/libassimp/code/AMF/AMFImporter_Material.cpp similarity index 99% rename from third_party/libassimp/code/AMFImporter_Material.cpp rename to third_party/libassimp/code/AMF/AMFImporter_Material.cpp index c9190bb92c..2f36df061b 100644 --- a/third_party/libassimp/code/AMFImporter_Material.cpp +++ b/third_party/libassimp/code/AMF/AMFImporter_Material.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/AMFImporter_Node.hpp b/third_party/libassimp/code/AMF/AMFImporter_Node.hpp similarity index 99% rename from third_party/libassimp/code/AMFImporter_Node.hpp rename to third_party/libassimp/code/AMF/AMFImporter_Node.hpp index 22b8f58cb1..a1bf9f0084 100644 --- a/third_party/libassimp/code/AMFImporter_Node.hpp +++ b/third_party/libassimp/code/AMF/AMFImporter_Node.hpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/AMFImporter_Postprocess.cpp b/third_party/libassimp/code/AMF/AMFImporter_Postprocess.cpp similarity index 98% rename from third_party/libassimp/code/AMFImporter_Postprocess.cpp rename to third_party/libassimp/code/AMF/AMFImporter_Postprocess.cpp index a6ee8fa2f7..79b5e15e2b 100644 --- a/third_party/libassimp/code/AMFImporter_Postprocess.cpp +++ b/third_party/libassimp/code/AMF/AMFImporter_Postprocess.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -66,7 +66,7 @@ aiColor4D AMFImporter::SPP_Material::GetColor(const float /*pX*/, const float /* aiColor4D tcol; // Check if stored data are supported. - if(Composition.size() != 0) + if(!Composition.empty()) { throw DeadlyImportError("IME. GetColor for composition"); } @@ -321,7 +321,7 @@ void AMFImporter::PostprocessHelper_SplitFacesByTextureID(std::list 0) pOutputList_Separated.push_back(face_list_cur); + if(!face_list_cur.empty()) pOutputList_Separated.push_back(face_list_cur); - } while(pInputList.size() > 0); + } while(!pInputList.empty()); } void AMFImporter::Postprocess_AddMetadata(const std::list& metadataList, aiNode& sceneNode) const @@ -712,7 +712,7 @@ std::list mesh_idx; }// for(const CAMFImporter_NodeElement* ne_child: pNodeElement.Child) // if meshes was created then assign new indices with current aiNode - if(mesh_idx.size() > 0) + if(!mesh_idx.empty()) { std::list::const_iterator mit = mesh_idx.begin(); @@ -787,7 +787,7 @@ std::list ch_node; }// for(const CAMFImporter_NodeElement* ne: pConstellation.Child) // copy found aiNode's as children - if(ch_node.size() == 0) throw DeadlyImportError(" must have at least one ."); + if(ch_node.empty()) throw DeadlyImportError(" must have at least one ."); size_t ch_idx = 0; @@ -883,13 +883,13 @@ nl_clean_loop: if(node_list.size() > 1) { // walk through all nodes - for(std::list::iterator nl_it = node_list.begin(); nl_it != node_list.end(); nl_it++) + for(std::list::iterator nl_it = node_list.begin(); nl_it != node_list.end(); ++nl_it) { // and try to find them in another top nodes. std::list::const_iterator next_it = nl_it; - next_it++; - for(; next_it != node_list.end(); next_it++) + ++next_it; + for(; next_it != node_list.end(); ++next_it) { if((*next_it)->FindNode((*nl_it)->mName) != nullptr) { @@ -907,7 +907,7 @@ nl_clean_loop: // // // Nodes - if(node_list.size() > 0) + if(!node_list.empty()) { std::list::const_iterator nl_it = node_list.begin(); @@ -924,7 +924,7 @@ nl_clean_loop: // // Meshes - if(mesh_list.size() > 0) + if(!mesh_list.empty()) { std::list::const_iterator ml_it = mesh_list.begin(); diff --git a/third_party/libassimp/code/ASELoader.cpp b/third_party/libassimp/code/ASE/ASELoader.cpp similarity index 99% rename from third_party/libassimp/code/ASELoader.cpp rename to third_party/libassimp/code/ASE/ASELoader.cpp index 1808f25e27..8e99214a84 100644 --- a/third_party/libassimp/code/ASELoader.cpp +++ b/third_party/libassimp/code/ASE/ASELoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -53,7 +53,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "ASELoader.h" #include #include -#include "TargetAnimation.h" +#include "Common/TargetAnimation.h" + #include #include #include @@ -88,23 +89,25 @@ ASEImporter::ASEImporter() , mBuffer() , pcScene() , configRecomputeNormals() -, noSkeletonMesh() -{} +, noSkeletonMesh() { + // empty +} // ------------------------------------------------------------------------------------------------ // Destructor, private as well -ASEImporter::~ASEImporter() -{} +ASEImporter::~ASEImporter() { + // empty +} // ------------------------------------------------------------------------------------------------ // Returns whether the class can handle the format of the given file. -bool ASEImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool cs) const -{ +bool ASEImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool cs) const { // check file extension const std::string extension = GetExtension(pFile); - if( extension == "ase" || extension == "ask") + if (extension == "ase" || extension == "ask") { return true; + } if ((!extension.length() || cs) && pIOHandler) { const char* tokens[] = {"*3dsmax_asciiexport"}; @@ -115,15 +118,13 @@ bool ASEImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool // ------------------------------------------------------------------------------------------------ // Loader meta information -const aiImporterDesc* ASEImporter::GetInfo () const -{ +const aiImporterDesc* ASEImporter::GetInfo () const { return &desc; } // ------------------------------------------------------------------------------------------------ // Setup configuration options -void ASEImporter::SetupProperties(const Importer* pImp) -{ +void ASEImporter::SetupProperties(const Importer* pImp) { configRecomputeNormals = (pImp->GetPropertyInteger( AI_CONFIG_IMPORT_ASE_RECONSTRUCT_NORMALS,1) ? true : false); @@ -133,12 +134,11 @@ void ASEImporter::SetupProperties(const Importer* pImp) // ------------------------------------------------------------------------------------------------ // Imports the given file into the given scene structure. void ASEImporter::InternReadFile( const std::string& pFile, - aiScene* pScene, IOSystem* pIOHandler) -{ + aiScene* pScene, IOSystem* pIOHandler) { std::unique_ptr file( pIOHandler->Open( pFile, "rb")); // Check whether we can read from the file - if( file.get() == NULL) { + if( file.get() == nullptr) { throw DeadlyImportError( "Failed to open ASE file " + pFile + "."); } @@ -1299,7 +1299,7 @@ void ASEImporter::BuildMaterialIndices() } } - // Dekete our temporary array + // Delete our temporary array delete[] pcIntMaterials; } diff --git a/third_party/libassimp/code/ASELoader.h b/third_party/libassimp/code/ASE/ASELoader.h similarity index 99% rename from third_party/libassimp/code/ASELoader.h rename to third_party/libassimp/code/ASE/ASELoader.h index 7f71bf49d6..b497aa48b8 100644 --- a/third_party/libassimp/code/ASELoader.h +++ b/third_party/libassimp/code/ASE/ASELoader.h @@ -2,8 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team - +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/ASEParser.cpp b/third_party/libassimp/code/ASE/ASEParser.cpp similarity index 99% rename from third_party/libassimp/code/ASEParser.cpp rename to third_party/libassimp/code/ASE/ASEParser.cpp index 298c6fe61c..913e7b1182 100644 --- a/third_party/libassimp/code/ASEParser.cpp +++ b/third_party/libassimp/code/ASE/ASEParser.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -45,20 +45,19 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * @brief Implementation of the ASE parser class */ - #ifndef ASSIMP_BUILD_NO_ASE_IMPORTER #ifndef ASSIMP_BUILD_NO_3DS_IMPORTER // internal headers -#include "TextureTransform.h" +#include "PostProcessing/TextureTransform.h" #include "ASELoader.h" + #include #include using namespace Assimp; using namespace Assimp::ASE; - // ------------------------------------------------------------------------------------------------ // Begin an ASE parsing function diff --git a/third_party/libassimp/code/ASEParser.h b/third_party/libassimp/code/ASE/ASEParser.h similarity index 99% rename from third_party/libassimp/code/ASEParser.h rename to third_party/libassimp/code/ASE/ASEParser.h index 305a3f3d6e..988cbda8db 100644 --- a/third_party/libassimp/code/ASEParser.h +++ b/third_party/libassimp/code/ASE/ASEParser.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -57,7 +57,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include // ASE is quite similar to 3ds. We can reuse some structures -#include "3DSLoader.h" +#include "3DS/3DSLoader.h" namespace Assimp { namespace ASE { @@ -188,10 +188,11 @@ struct Animation { } mRotationType, mScalingType, mPositionType; Animation() AI_NO_EXCEPT - : mRotationType (TRACK) - , mScalingType (TRACK) - , mPositionType (TRACK) - {} + : mRotationType (TRACK) + , mScalingType (TRACK) + , mPositionType (TRACK) { + // empty + } //! List of track rotation keyframes std::vector< aiQuatKey > akeyRotations; @@ -243,7 +244,6 @@ struct BaseNode { mTargetPosition.x = qnan; } - //! Name of the mesh std::string mName; diff --git a/third_party/libassimp/code/AssbinExporter.cpp b/third_party/libassimp/code/Assbin/AssbinExporter.cpp similarity index 99% rename from third_party/libassimp/code/AssbinExporter.cpp rename to third_party/libassimp/code/Assbin/AssbinExporter.cpp index f49389f785..76c823f826 100644 --- a/third_party/libassimp/code/AssbinExporter.cpp +++ b/third_party/libassimp/code/Assbin/AssbinExporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -46,12 +46,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_EXPORT #ifndef ASSIMP_BUILD_NO_ASSBIN_EXPORTER -#include "assbin_chunks.h" +#include "Common/assbin_chunks.h" +#include "PostProcessing/ProcessHelper.h" + #include #include #include #include -#include "ProcessHelper.h" #include #ifdef ASSIMP_BUILD_NO_OWN_ZLIB @@ -760,7 +761,12 @@ public: if (!out) return; time_t tt = time(NULL); +#if _WIN32 tm* p = gmtime(&tt); +#else + struct tm now; + tm* p = gmtime_r(&tt, &now); +#endif // header char s[64]; diff --git a/third_party/libassimp/code/AssbinExporter.h b/third_party/libassimp/code/Assbin/AssbinExporter.h similarity index 98% rename from third_party/libassimp/code/AssbinExporter.h rename to third_party/libassimp/code/Assbin/AssbinExporter.h index ee70d78b65..3e13639bbf 100644 --- a/third_party/libassimp/code/AssbinExporter.h +++ b/third_party/libassimp/code/Assbin/AssbinExporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/AssbinLoader.cpp b/third_party/libassimp/code/Assbin/AssbinLoader.cpp similarity index 99% rename from third_party/libassimp/code/AssbinLoader.cpp rename to third_party/libassimp/code/Assbin/AssbinLoader.cpp index 321a0cfecd..becc3f8fc9 100644 --- a/third_party/libassimp/code/AssbinLoader.cpp +++ b/third_party/libassimp/code/Assbin/AssbinLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -50,8 +50,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_ASSBIN_IMPORTER // internal headers -#include "AssbinLoader.h" -#include "assbin_chunks.h" +#include "Assbin/AssbinLoader.h" +#include "Common/assbin_chunks.h" #include #include #include @@ -68,7 +68,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using namespace Assimp; static const aiImporterDesc desc = { - ".assbin Importer", + "Assimp Binary Importer", "Gargaj / Conspiracy", "", "", @@ -708,7 +708,7 @@ void AssbinImporter::InternReadFile( const std::string& pFile, aiScene* pScene, unsigned char * uncompressedData = new unsigned char[ uncompressedSize ]; - int res = uncompress( uncompressedData, &uncompressedSize, compressedData, len ); + int res = uncompress( uncompressedData, &uncompressedSize, compressedData, (uLong) len ); if(res != Z_OK) { delete [] uncompressedData; diff --git a/third_party/libassimp/code/AssbinLoader.h b/third_party/libassimp/code/Assbin/AssbinLoader.h similarity index 98% rename from third_party/libassimp/code/AssbinLoader.h rename to third_party/libassimp/code/Assbin/AssbinLoader.h index 37799a2c8c..9f2dde1251 100644 --- a/third_party/libassimp/code/AssbinLoader.h +++ b/third_party/libassimp/code/Assbin/AssbinLoader.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/Assjson/cencode.c b/third_party/libassimp/code/Assjson/cencode.c new file mode 100644 index 0000000000..db99e7efa4 --- /dev/null +++ b/third_party/libassimp/code/Assjson/cencode.c @@ -0,0 +1,109 @@ +/* +cencoder.c - c source to a base64 encoding algorithm implementation + +This is part of the libb64 project, and has been placed in the public domain. +For details, see http://sourceforge.net/projects/libb64 +*/ + +#include "cencode.h" // changed from + +const int CHARS_PER_LINE = 72; + +void base64_init_encodestate(base64_encodestate* state_in) +{ + state_in->step = step_A; + state_in->result = 0; + state_in->stepcount = 0; +} + +char base64_encode_value(char value_in) +{ + static const char* encoding = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + if (value_in > 63) return '='; + return encoding[(int)value_in]; +} + +int base64_encode_block(const char* plaintext_in, int length_in, char* code_out, base64_encodestate* state_in) +{ + const char* plainchar = plaintext_in; + const char* const plaintextend = plaintext_in + length_in; + char* codechar = code_out; + char result; + char fragment; + + result = state_in->result; + + switch (state_in->step) + { + while (1) + { + case step_A: + if (plainchar == plaintextend) + { + state_in->result = result; + state_in->step = step_A; + return codechar - code_out; + } + fragment = *plainchar++; + result = (fragment & 0x0fc) >> 2; + *codechar++ = base64_encode_value(result); + result = (fragment & 0x003) << 4; + case step_B: + if (plainchar == plaintextend) + { + state_in->result = result; + state_in->step = step_B; + return codechar - code_out; + } + fragment = *plainchar++; + result |= (fragment & 0x0f0) >> 4; + *codechar++ = base64_encode_value(result); + result = (fragment & 0x00f) << 2; + case step_C: + if (plainchar == plaintextend) + { + state_in->result = result; + state_in->step = step_C; + return codechar - code_out; + } + fragment = *plainchar++; + result |= (fragment & 0x0c0) >> 6; + *codechar++ = base64_encode_value(result); + result = (fragment & 0x03f) >> 0; + *codechar++ = base64_encode_value(result); + + ++(state_in->stepcount); + if (state_in->stepcount == CHARS_PER_LINE/4) + { + *codechar++ = '\n'; + state_in->stepcount = 0; + } + } + } + /* control should not reach here */ + return codechar - code_out; +} + +int base64_encode_blockend(char* code_out, base64_encodestate* state_in) +{ + char* codechar = code_out; + + switch (state_in->step) + { + case step_B: + *codechar++ = base64_encode_value(state_in->result); + *codechar++ = '='; + *codechar++ = '='; + break; + case step_C: + *codechar++ = base64_encode_value(state_in->result); + *codechar++ = '='; + break; + case step_A: + break; + } + *codechar++ = '\n'; + + return codechar - code_out; +} + diff --git a/third_party/libassimp/code/Assjson/cencode.h b/third_party/libassimp/code/Assjson/cencode.h new file mode 100644 index 0000000000..c1e3464af3 --- /dev/null +++ b/third_party/libassimp/code/Assjson/cencode.h @@ -0,0 +1,31 @@ +/* +cencode.h - c header for a base64 encoding algorithm + +This is part of the libb64 project, and has been placed in the public domain. +For details, see http://sourceforge.net/projects/libb64 +*/ + +#ifndef BASE64_CENCODE_H +#define BASE64_CENCODE_H + +typedef enum +{ + step_A, step_B, step_C +} base64_encodestep; + +typedef struct +{ + base64_encodestep step; + char result; + int stepcount; +} base64_encodestate; + +void base64_init_encodestate(base64_encodestate* state_in); + +char base64_encode_value(char value_in); + +int base64_encode_block(const char* plaintext_in, int length_in, char* code_out, base64_encodestate* state_in); + +int base64_encode_blockend(char* code_out, base64_encodestate* state_in); + +#endif /* BASE64_CENCODE_H */ diff --git a/third_party/libassimp/code/Assjson/json_exporter.cpp b/third_party/libassimp/code/Assjson/json_exporter.cpp new file mode 100644 index 0000000000..e9fa72496c --- /dev/null +++ b/third_party/libassimp/code/Assjson/json_exporter.cpp @@ -0,0 +1,809 @@ +/* +Assimp2Json +Copyright (c) 2011, Alexander C. Gessler + +Licensed under a 3-clause BSD license. See the LICENSE file for more information. + +*/ + +#ifndef ASSIMP_BUILD_NO_EXPORT +#ifndef ASSIMP_BUILD_NO_ASSJSON_EXPORTER + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#define CURRENT_FORMAT_VERSION 100 + +// grab scoped_ptr from assimp to avoid a dependency on boost. +//#include + +#include "mesh_splitter.h" + +extern "C" { + #include "cencode.h" +} +namespace Assimp { + +void ExportAssimp2Json(const char*, Assimp::IOSystem*, const aiScene*, const Assimp::ExportProperties*); + +// small utility class to simplify serializing the aiScene to Json +class JSONWriter { +public: + enum { + Flag_DoNotIndent = 0x1, + Flag_WriteSpecialFloats = 0x2, + }; + + JSONWriter(Assimp::IOStream& out, unsigned int flags = 0u) + : out(out) + , first() + , flags(flags) { + // make sure that all formatting happens using the standard, C locale and not the user's current locale + buff.imbue(std::locale("C")); + } + + ~JSONWriter() { + Flush(); + } + + void Flush() { + const std::string s = buff.str(); + out.Write(s.c_str(), s.length(), 1); + buff.clear(); + } + + void PushIndent() { + indent += '\t'; + } + + void PopIndent() { + indent.erase(indent.end() - 1); + } + + void Key(const std::string& name) { + AddIndentation(); + Delimit(); + buff << '\"' + name + "\": "; + } + + template + void Element(const Literal& name) { + AddIndentation(); + Delimit(); + + LiteralToString(buff, name) << '\n'; + } + + template + void SimpleValue(const Literal& s) { + LiteralToString(buff, s) << '\n'; + } + + void SimpleValue(const void* buffer, size_t len) { + base64_encodestate s; + base64_init_encodestate(&s); + + char* const out = new char[std::max(len * 2, static_cast(16u))]; + const int n = base64_encode_block(reinterpret_cast(buffer), static_cast(len), out, &s); + out[n + base64_encode_blockend(out + n, &s)] = '\0'; + + // base64 encoding may add newlines, but JSON strings may not contain 'real' newlines + // (only escaped ones). Remove any newlines in out. + for (char* cur = out; *cur; ++cur) { + if (*cur == '\n') { + *cur = ' '; + } + } + + buff << '\"' << out << "\"\n"; + delete[] out; + } + + void StartObj(bool is_element = false) { + // if this appears as a plain array element, we need to insert a delimiter and we should also indent it + if (is_element) { + AddIndentation(); + if (!first) { + buff << ','; + } + } + first = true; + buff << "{\n"; + PushIndent(); + } + + void EndObj() { + PopIndent(); + AddIndentation(); + first = false; + buff << "}\n"; + } + + void StartArray(bool is_element = false) { + // if this appears as a plain array element, we need to insert a delimiter and we should also indent it + if (is_element) { + AddIndentation(); + if (!first) { + buff << ','; + } + } + first = true; + buff << "[\n"; + PushIndent(); + } + + void EndArray() { + PopIndent(); + AddIndentation(); + buff << "]\n"; + first = false; + } + + void AddIndentation() { + if (!(flags & Flag_DoNotIndent)) { + buff << indent; + } + } + + void Delimit() { + if (!first) { + buff << ','; + } + else { + buff << ' '; + first = false; + } + } + +private: + template + std::stringstream& LiteralToString(std::stringstream& stream, const Literal& s) { + stream << s; + return stream; + } + + std::stringstream& LiteralToString(std::stringstream& stream, const aiString& s) { + std::string t; + + // escape backslashes and single quotes, both would render the JSON invalid if left as is + t.reserve(s.length); + for (size_t i = 0; i < s.length; ++i) { + + if (s.data[i] == '\\' || s.data[i] == '\'' || s.data[i] == '\"') { + t.push_back('\\'); + } + + t.push_back(s.data[i]); + } + stream << "\""; + stream << t; + stream << "\""; + return stream; + } + + std::stringstream& LiteralToString(std::stringstream& stream, float f) { + if (!std::numeric_limits::is_iec559) { + // on a non IEEE-754 platform, we make no assumptions about the representation or existence + // of special floating-point numbers. + stream << f; + return stream; + } + + // JSON does not support writing Inf/Nan + // [RFC 4672: "Numeric values that cannot be represented as sequences of digits + // (such as Infinity and NaN) are not permitted."] + // Nevertheless, many parsers will accept the special keywords Infinity, -Infinity and NaN + if (std::numeric_limits::infinity() == fabs(f)) { + if (flags & Flag_WriteSpecialFloats) { + stream << (f < 0 ? "\"-" : "\"") + std::string("Infinity\""); + return stream; + } + // we should print this warning, but we can't - this is called from within a generic assimp exporter, we cannot use cerr + // std::cerr << "warning: cannot represent infinite number literal, substituting 0 instead (use -i flag to enforce Infinity/NaN)" << std::endl; + stream << "0.0"; + return stream; + } + // f!=f is the most reliable test for NaNs that I know of + else if (f != f) { + if (flags & Flag_WriteSpecialFloats) { + stream << "\"NaN\""; + return stream; + } + // we should print this warning, but we can't - this is called from within a generic assimp exporter, we cannot use cerr + // std::cerr << "warning: cannot represent infinite number literal, substituting 0 instead (use -i flag to enforce Infinity/NaN)" << std::endl; + stream << "0.0"; + return stream; + } + + stream << f; + return stream; + } + +private: + Assimp::IOStream& out; + std::string indent, newline; + std::stringstream buff; + bool first; + + unsigned int flags; +}; + +void Write(JSONWriter& out, const aiVector3D& ai, bool is_elem = true) { + out.StartArray(is_elem); + out.Element(ai.x); + out.Element(ai.y); + out.Element(ai.z); + out.EndArray(); +} + +void Write(JSONWriter& out, const aiQuaternion& ai, bool is_elem = true) { + out.StartArray(is_elem); + out.Element(ai.w); + out.Element(ai.x); + out.Element(ai.y); + out.Element(ai.z); + out.EndArray(); +} + +void Write(JSONWriter& out, const aiColor3D& ai, bool is_elem = true) { + out.StartArray(is_elem); + out.Element(ai.r); + out.Element(ai.g); + out.Element(ai.b); + out.EndArray(); +} + +void Write(JSONWriter& out, const aiMatrix4x4& ai, bool is_elem = true) { + out.StartArray(is_elem); + for (unsigned int x = 0; x < 4; ++x) { + for (unsigned int y = 0; y < 4; ++y) { + out.Element(ai[x][y]); + } + } + out.EndArray(); +} + +void Write(JSONWriter& out, const aiBone& ai, bool is_elem = true) { + out.StartObj(is_elem); + + out.Key("name"); + out.SimpleValue(ai.mName); + + out.Key("offsetmatrix"); + Write(out, ai.mOffsetMatrix, false); + + out.Key("weights"); + out.StartArray(); + for (unsigned int i = 0; i < ai.mNumWeights; ++i) { + out.StartArray(true); + out.Element(ai.mWeights[i].mVertexId); + out.Element(ai.mWeights[i].mWeight); + out.EndArray(); + } + out.EndArray(); + out.EndObj(); +} + +void Write(JSONWriter& out, const aiFace& ai, bool is_elem = true) { + out.StartArray(is_elem); + for (unsigned int i = 0; i < ai.mNumIndices; ++i) { + out.Element(ai.mIndices[i]); + } + out.EndArray(); +} + +void Write(JSONWriter& out, const aiMesh& ai, bool is_elem = true) { + out.StartObj(is_elem); + + out.Key("name"); + out.SimpleValue(ai.mName); + + out.Key("materialindex"); + out.SimpleValue(ai.mMaterialIndex); + + out.Key("primitivetypes"); + out.SimpleValue(ai.mPrimitiveTypes); + + out.Key("vertices"); + out.StartArray(); + for (unsigned int i = 0; i < ai.mNumVertices; ++i) { + out.Element(ai.mVertices[i].x); + out.Element(ai.mVertices[i].y); + out.Element(ai.mVertices[i].z); + } + out.EndArray(); + + if (ai.HasNormals()) { + out.Key("normals"); + out.StartArray(); + for (unsigned int i = 0; i < ai.mNumVertices; ++i) { + out.Element(ai.mNormals[i].x); + out.Element(ai.mNormals[i].y); + out.Element(ai.mNormals[i].z); + } + out.EndArray(); + } + + if (ai.HasTangentsAndBitangents()) { + out.Key("tangents"); + out.StartArray(); + for (unsigned int i = 0; i < ai.mNumVertices; ++i) { + out.Element(ai.mTangents[i].x); + out.Element(ai.mTangents[i].y); + out.Element(ai.mTangents[i].z); + } + out.EndArray(); + + out.Key("bitangents"); + out.StartArray(); + for (unsigned int i = 0; i < ai.mNumVertices; ++i) { + out.Element(ai.mBitangents[i].x); + out.Element(ai.mBitangents[i].y); + out.Element(ai.mBitangents[i].z); + } + out.EndArray(); + } + + if (ai.GetNumUVChannels()) { + out.Key("numuvcomponents"); + out.StartArray(); + for (unsigned int n = 0; n < ai.GetNumUVChannels(); ++n) { + out.Element(ai.mNumUVComponents[n]); + } + out.EndArray(); + + out.Key("texturecoords"); + out.StartArray(); + for (unsigned int n = 0; n < ai.GetNumUVChannels(); ++n) { + const unsigned int numc = ai.mNumUVComponents[n] ? ai.mNumUVComponents[n] : 2; + + out.StartArray(true); + for (unsigned int i = 0; i < ai.mNumVertices; ++i) { + for (unsigned int c = 0; c < numc; ++c) { + out.Element(ai.mTextureCoords[n][i][c]); + } + } + out.EndArray(); + } + out.EndArray(); + } + + if (ai.GetNumColorChannels()) { + out.Key("colors"); + out.StartArray(); + for (unsigned int n = 0; n < ai.GetNumColorChannels(); ++n) { + out.StartArray(true); + for (unsigned int i = 0; i < ai.mNumVertices; ++i) { + out.Element(ai.mColors[n][i].r); + out.Element(ai.mColors[n][i].g); + out.Element(ai.mColors[n][i].b); + out.Element(ai.mColors[n][i].a); + } + out.EndArray(); + } + out.EndArray(); + } + + if (ai.mNumBones) { + out.Key("bones"); + out.StartArray(); + for (unsigned int n = 0; n < ai.mNumBones; ++n) { + Write(out, *ai.mBones[n]); + } + out.EndArray(); + } + + out.Key("faces"); + out.StartArray(); + for (unsigned int n = 0; n < ai.mNumFaces; ++n) { + Write(out, ai.mFaces[n]); + } + out.EndArray(); + + out.EndObj(); +} + +void Write(JSONWriter& out, const aiNode& ai, bool is_elem = true) { + out.StartObj(is_elem); + + out.Key("name"); + out.SimpleValue(ai.mName); + + out.Key("transformation"); + Write(out, ai.mTransformation, false); + + if (ai.mNumMeshes) { + out.Key("meshes"); + out.StartArray(); + for (unsigned int n = 0; n < ai.mNumMeshes; ++n) { + out.Element(ai.mMeshes[n]); + } + out.EndArray(); + } + + if (ai.mNumChildren) { + out.Key("children"); + out.StartArray(); + for (unsigned int n = 0; n < ai.mNumChildren; ++n) { + Write(out, *ai.mChildren[n]); + } + out.EndArray(); + } + + out.EndObj(); +} + +void Write(JSONWriter& out, const aiMaterial& ai, bool is_elem = true) { + out.StartObj(is_elem); + + out.Key("properties"); + out.StartArray(); + for (unsigned int i = 0; i < ai.mNumProperties; ++i) { + const aiMaterialProperty* const prop = ai.mProperties[i]; + out.StartObj(true); + out.Key("key"); + out.SimpleValue(prop->mKey); + out.Key("semantic"); + out.SimpleValue(prop->mSemantic); + out.Key("index"); + out.SimpleValue(prop->mIndex); + + out.Key("type"); + out.SimpleValue(prop->mType); + + out.Key("value"); + switch (prop->mType) { + case aiPTI_Float: + if (prop->mDataLength / sizeof(float) > 1) { + out.StartArray(); + for (unsigned int i = 0; i < prop->mDataLength / sizeof(float); ++i) { + out.Element(reinterpret_cast(prop->mData)[i]); + } + out.EndArray(); + } + else { + out.SimpleValue(*reinterpret_cast(prop->mData)); + } + break; + + case aiPTI_Integer: + if (prop->mDataLength / sizeof(int) > 1) { + out.StartArray(); + for (unsigned int i = 0; i < prop->mDataLength / sizeof(int); ++i) { + out.Element(reinterpret_cast(prop->mData)[i]); + } + out.EndArray(); + } else { + out.SimpleValue(*reinterpret_cast(prop->mData)); + } + break; + + case aiPTI_String: + { + aiString s; + aiGetMaterialString(&ai, prop->mKey.data, prop->mSemantic, prop->mIndex, &s); + out.SimpleValue(s); + } + break; + case aiPTI_Buffer: + { + // binary data is written as series of hex-encoded octets + out.SimpleValue(prop->mData, prop->mDataLength); + } + break; + default: + assert(false); + } + + out.EndObj(); + } + + out.EndArray(); + out.EndObj(); +} + +void Write(JSONWriter& out, const aiTexture& ai, bool is_elem = true) { + out.StartObj(is_elem); + + out.Key("width"); + out.SimpleValue(ai.mWidth); + + out.Key("height"); + out.SimpleValue(ai.mHeight); + + out.Key("formathint"); + out.SimpleValue(aiString(ai.achFormatHint)); + + out.Key("data"); + if (!ai.mHeight) { + out.SimpleValue(ai.pcData, ai.mWidth); + } + else { + out.StartArray(); + for (unsigned int y = 0; y < ai.mHeight; ++y) { + out.StartArray(true); + for (unsigned int x = 0; x < ai.mWidth; ++x) { + const aiTexel& tx = ai.pcData[y*ai.mWidth + x]; + out.StartArray(true); + out.Element(static_cast(tx.r)); + out.Element(static_cast(tx.g)); + out.Element(static_cast(tx.b)); + out.Element(static_cast(tx.a)); + out.EndArray(); + } + out.EndArray(); + } + out.EndArray(); + } + + out.EndObj(); +} + +void Write(JSONWriter& out, const aiLight& ai, bool is_elem = true) { + out.StartObj(is_elem); + + out.Key("name"); + out.SimpleValue(ai.mName); + + out.Key("type"); + out.SimpleValue(ai.mType); + + if (ai.mType == aiLightSource_SPOT || ai.mType == aiLightSource_UNDEFINED) { + out.Key("angleinnercone"); + out.SimpleValue(ai.mAngleInnerCone); + + out.Key("angleoutercone"); + out.SimpleValue(ai.mAngleOuterCone); + } + + out.Key("attenuationconstant"); + out.SimpleValue(ai.mAttenuationConstant); + + out.Key("attenuationlinear"); + out.SimpleValue(ai.mAttenuationLinear); + + out.Key("attenuationquadratic"); + out.SimpleValue(ai.mAttenuationQuadratic); + + out.Key("diffusecolor"); + Write(out, ai.mColorDiffuse, false); + + out.Key("specularcolor"); + Write(out, ai.mColorSpecular, false); + + out.Key("ambientcolor"); + Write(out, ai.mColorAmbient, false); + + if (ai.mType != aiLightSource_POINT) { + out.Key("direction"); + Write(out, ai.mDirection, false); + + } + + if (ai.mType != aiLightSource_DIRECTIONAL) { + out.Key("position"); + Write(out, ai.mPosition, false); + } + + out.EndObj(); +} + +void Write(JSONWriter& out, const aiNodeAnim& ai, bool is_elem = true) { + out.StartObj(is_elem); + + out.Key("name"); + out.SimpleValue(ai.mNodeName); + + out.Key("prestate"); + out.SimpleValue(ai.mPreState); + + out.Key("poststate"); + out.SimpleValue(ai.mPostState); + + if (ai.mNumPositionKeys) { + out.Key("positionkeys"); + out.StartArray(); + for (unsigned int n = 0; n < ai.mNumPositionKeys; ++n) { + const aiVectorKey& pos = ai.mPositionKeys[n]; + out.StartArray(true); + out.Element(pos.mTime); + Write(out, pos.mValue); + out.EndArray(); + } + out.EndArray(); + } + + if (ai.mNumRotationKeys) { + out.Key("rotationkeys"); + out.StartArray(); + for (unsigned int n = 0; n < ai.mNumRotationKeys; ++n) { + const aiQuatKey& rot = ai.mRotationKeys[n]; + out.StartArray(true); + out.Element(rot.mTime); + Write(out, rot.mValue); + out.EndArray(); + } + out.EndArray(); + } + + if (ai.mNumScalingKeys) { + out.Key("scalingkeys"); + out.StartArray(); + for (unsigned int n = 0; n < ai.mNumScalingKeys; ++n) { + const aiVectorKey& scl = ai.mScalingKeys[n]; + out.StartArray(true); + out.Element(scl.mTime); + Write(out, scl.mValue); + out.EndArray(); + } + out.EndArray(); + } + out.EndObj(); +} + +void Write(JSONWriter& out, const aiAnimation& ai, bool is_elem = true) { + out.StartObj(is_elem); + + out.Key("name"); + out.SimpleValue(ai.mName); + + out.Key("tickspersecond"); + out.SimpleValue(ai.mTicksPerSecond); + + out.Key("duration"); + out.SimpleValue(ai.mDuration); + + out.Key("channels"); + out.StartArray(); + for (unsigned int n = 0; n < ai.mNumChannels; ++n) { + Write(out, *ai.mChannels[n]); + } + out.EndArray(); + out.EndObj(); +} + +void Write(JSONWriter& out, const aiCamera& ai, bool is_elem = true) { + out.StartObj(is_elem); + + out.Key("name"); + out.SimpleValue(ai.mName); + + out.Key("aspect"); + out.SimpleValue(ai.mAspect); + + out.Key("clipplanefar"); + out.SimpleValue(ai.mClipPlaneFar); + + out.Key("clipplanenear"); + out.SimpleValue(ai.mClipPlaneNear); + + out.Key("horizontalfov"); + out.SimpleValue(ai.mHorizontalFOV); + + out.Key("up"); + Write(out, ai.mUp, false); + + out.Key("lookat"); + Write(out, ai.mLookAt, false); + + out.EndObj(); +} + +void WriteFormatInfo(JSONWriter& out) { + out.StartObj(); + out.Key("format"); + out.SimpleValue("\"assimp2json\""); + out.Key("version"); + out.SimpleValue(CURRENT_FORMAT_VERSION); + out.EndObj(); +} + +void Write(JSONWriter& out, const aiScene& ai) { + out.StartObj(); + + out.Key("__metadata__"); + WriteFormatInfo(out); + + out.Key("rootnode"); + Write(out, *ai.mRootNode, false); + + out.Key("flags"); + out.SimpleValue(ai.mFlags); + + if (ai.HasMeshes()) { + out.Key("meshes"); + out.StartArray(); + for (unsigned int n = 0; n < ai.mNumMeshes; ++n) { + Write(out, *ai.mMeshes[n]); + } + out.EndArray(); + } + + if (ai.HasMaterials()) { + out.Key("materials"); + out.StartArray(); + for (unsigned int n = 0; n < ai.mNumMaterials; ++n) { + Write(out, *ai.mMaterials[n]); + } + out.EndArray(); + } + + if (ai.HasAnimations()) { + out.Key("animations"); + out.StartArray(); + for (unsigned int n = 0; n < ai.mNumAnimations; ++n) { + Write(out, *ai.mAnimations[n]); + } + out.EndArray(); + } + + if (ai.HasLights()) { + out.Key("lights"); + out.StartArray(); + for (unsigned int n = 0; n < ai.mNumLights; ++n) { + Write(out, *ai.mLights[n]); + } + out.EndArray(); + } + + if (ai.HasCameras()) { + out.Key("cameras"); + out.StartArray(); + for (unsigned int n = 0; n < ai.mNumCameras; ++n) { + Write(out, *ai.mCameras[n]); + } + out.EndArray(); + } + + if (ai.HasTextures()) { + out.Key("textures"); + out.StartArray(); + for (unsigned int n = 0; n < ai.mNumTextures; ++n) { + Write(out, *ai.mTextures[n]); + } + out.EndArray(); + } + out.EndObj(); +} + + +void ExportAssimp2Json(const char* file, Assimp::IOSystem* io, const aiScene* scene, const Assimp::ExportProperties*) { + std::unique_ptr str(io->Open(file, "wt")); + if (!str) { + //throw Assimp::DeadlyExportError("could not open output file"); + } + + // get a copy of the scene so we can modify it + aiScene* scenecopy_tmp; + aiCopyScene(scene, &scenecopy_tmp); + + try { + // split meshes so they fit into a 16 bit index buffer + MeshSplitter splitter; + splitter.SetLimit(1 << 16); + splitter.Execute(scenecopy_tmp); + + // XXX Flag_WriteSpecialFloats is turned on by default, right now we don't have a configuration interface for exporters + JSONWriter s(*str, JSONWriter::Flag_WriteSpecialFloats); + Write(s, *scenecopy_tmp); + + } + catch (...) { + aiFreeScene(scenecopy_tmp); + throw; + } + aiFreeScene(scenecopy_tmp); +} + +} + +#endif // ASSIMP_BUILD_NO_ASSJSON_EXPORTER +#endif // ASSIMP_BUILD_NO_EXPORT diff --git a/third_party/libassimp/code/Assjson/mesh_splitter.cpp b/third_party/libassimp/code/Assjson/mesh_splitter.cpp new file mode 100644 index 0000000000..24385f9a07 --- /dev/null +++ b/third_party/libassimp/code/Assjson/mesh_splitter.cpp @@ -0,0 +1,320 @@ +/* +Assimp2Json +Copyright (c) 2011, Alexander C. Gessler + +Licensed under a 3-clause BSD license. See the LICENSE file for more information. + +*/ + +#include "mesh_splitter.h" + +#include + +// ---------------------------------------------------------------------------- +// Note: this is largely based on assimp's SplitLargeMeshes_Vertex process. +// it is refactored and the coding style is slightly improved, though. +// ---------------------------------------------------------------------------- + +// ------------------------------------------------------------------------------------------------ +// Executes the post processing step on the given imported data. +void MeshSplitter::Execute( aiScene* pScene) { + std::vector > source_mesh_map; + + for( unsigned int a = 0; a < pScene->mNumMeshes; a++) { + SplitMesh(a, pScene->mMeshes[a],source_mesh_map); + } + + const unsigned int size = static_cast(source_mesh_map.size()); + if (size != pScene->mNumMeshes) { + // it seems something has been split. rebuild the mesh list + delete[] pScene->mMeshes; + pScene->mNumMeshes = size; + pScene->mMeshes = new aiMesh*[size](); + + for (unsigned int i = 0; i < size;++i) { + pScene->mMeshes[i] = source_mesh_map[i].first; + } + + // now we need to update all nodes + UpdateNode(pScene->mRootNode,source_mesh_map); + } +} + + +// ------------------------------------------------------------------------------------------------ +void MeshSplitter::UpdateNode(aiNode* pcNode, const std::vector >& source_mesh_map) { + // TODO: should better use std::(multi)set for source_mesh_map. + + // for every index in out list build a new entry + std::vector aiEntries; + aiEntries.reserve(pcNode->mNumMeshes + 1); + for (unsigned int i = 0; i < pcNode->mNumMeshes;++i) { + for (unsigned int a = 0, end = static_cast(source_mesh_map.size()); a < end;++a) { + if (source_mesh_map[a].second == pcNode->mMeshes[i]) { + aiEntries.push_back(a); + } + } + } + + // now build the new list + delete pcNode->mMeshes; + pcNode->mNumMeshes = static_cast(aiEntries.size()); + pcNode->mMeshes = new unsigned int[pcNode->mNumMeshes]; + + for (unsigned int b = 0; b < pcNode->mNumMeshes;++b) { + pcNode->mMeshes[b] = aiEntries[b]; + } + + // recursively update children + for (unsigned int i = 0, end = pcNode->mNumChildren; i < end;++i) { + UpdateNode ( pcNode->mChildren[i], source_mesh_map ); + } + return; +} + +#define WAS_NOT_COPIED 0xffffffff + +typedef std::pair PerVertexWeight; +typedef std::vector VertexWeightTable; + +// ------------------------------------------------------------------------------------------------ +VertexWeightTable* ComputeVertexBoneWeightTable(const aiMesh* pMesh) { + if (!pMesh || !pMesh->mNumVertices || !pMesh->mNumBones) { + return nullptr; + } + + VertexWeightTable* const avPerVertexWeights = new VertexWeightTable[pMesh->mNumVertices]; + for (unsigned int i = 0; i < pMesh->mNumBones;++i) { + + aiBone* bone = pMesh->mBones[i]; + for (unsigned int a = 0; a < bone->mNumWeights;++a) { + const aiVertexWeight& weight = bone->mWeights[a]; + avPerVertexWeights[weight.mVertexId].push_back( std::make_pair(i,weight.mWeight) ); + } + } + return avPerVertexWeights; +} + +// ------------------------------------------------------------------------------------------------ +void MeshSplitter :: SplitMesh(unsigned int a, aiMesh* in_mesh, std::vector >& source_mesh_map) { + // TODO: should better use std::(multi)set for source_mesh_map. + + if (in_mesh->mNumVertices <= LIMIT) { + source_mesh_map.push_back(std::make_pair(in_mesh,a)); + return; + } + + // build a per-vertex weight list if necessary + VertexWeightTable* avPerVertexWeights = ComputeVertexBoneWeightTable(in_mesh); + + // we need to split this mesh into sub meshes. Estimate submesh size + const unsigned int sub_meshes = (in_mesh->mNumVertices / LIMIT) + 1; + + // create a std::vector to remember which vertices have already + // been copied and to which position (i.e. output index) + std::vector was_copied_to; + was_copied_to.resize(in_mesh->mNumVertices,WAS_NOT_COPIED); + + // Try to find a good estimate for the number of output faces + // per mesh. Add 12.5% as buffer + unsigned int size_estimated = in_mesh->mNumFaces / sub_meshes; + size_estimated += size_estimated / 8; + + // now generate all submeshes + unsigned int base = 0; + while (true) { + const unsigned int out_vertex_index = LIMIT; + + aiMesh* out_mesh = new aiMesh(); + out_mesh->mNumVertices = 0; + out_mesh->mMaterialIndex = in_mesh->mMaterialIndex; + + // the name carries the adjacency information between the meshes + out_mesh->mName = in_mesh->mName; + + typedef std::vector BoneWeightList; + if (in_mesh->HasBones()) { + out_mesh->mBones = new aiBone*[in_mesh->mNumBones](); + } + + // clear the temporary helper array + if (base) { + std::fill(was_copied_to.begin(), was_copied_to.end(), WAS_NOT_COPIED); + } + + std::vector vFaces; + + // reserve enough storage for most cases + if (in_mesh->HasPositions()) { + out_mesh->mVertices = new aiVector3D[out_vertex_index]; + } + + if (in_mesh->HasNormals()) { + out_mesh->mNormals = new aiVector3D[out_vertex_index]; + } + + if (in_mesh->HasTangentsAndBitangents()) { + out_mesh->mTangents = new aiVector3D[out_vertex_index]; + out_mesh->mBitangents = new aiVector3D[out_vertex_index]; + } + + for (unsigned int c = 0; in_mesh->HasVertexColors(c);++c) { + out_mesh->mColors[c] = new aiColor4D[out_vertex_index]; + } + + for (unsigned int c = 0; in_mesh->HasTextureCoords(c);++c) { + out_mesh->mNumUVComponents[c] = in_mesh->mNumUVComponents[c]; + out_mesh->mTextureCoords[c] = new aiVector3D[out_vertex_index]; + } + vFaces.reserve(size_estimated); + + // (we will also need to copy the array of indices) + while (base < in_mesh->mNumFaces) { + const unsigned int iNumIndices = in_mesh->mFaces[base].mNumIndices; + + // doesn't catch degenerates but is quite fast + unsigned int iNeed = 0; + for (unsigned int v = 0; v < iNumIndices;++v) { + unsigned int index = in_mesh->mFaces[base].mIndices[v]; + + // check whether we do already have this vertex + if (WAS_NOT_COPIED == was_copied_to[index]) { + iNeed++; + } + } + if (out_mesh->mNumVertices + iNeed > out_vertex_index) { + // don't use this face + break; + } + + vFaces.push_back(aiFace()); + aiFace& rFace = vFaces.back(); + + // setup face type and number of indices + rFace.mNumIndices = iNumIndices; + rFace.mIndices = new unsigned int[iNumIndices]; + + // need to update the output primitive types + switch (rFace.mNumIndices) + { + case 1: + out_mesh->mPrimitiveTypes |= aiPrimitiveType_POINT; + break; + case 2: + out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE; + break; + case 3: + out_mesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE; + break; + default: + out_mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON; + } + + // and copy the contents of the old array, offset them by current base + for (unsigned int v = 0; v < iNumIndices;++v) { + const unsigned int index = in_mesh->mFaces[base].mIndices[v]; + + // check whether we do already have this vertex + if (WAS_NOT_COPIED != was_copied_to[index]) { + rFace.mIndices[v] = was_copied_to[index]; + continue; + } + + // copy positions + out_mesh->mVertices[out_mesh->mNumVertices] = (in_mesh->mVertices[index]); + + // copy normals + if (in_mesh->HasNormals()) { + out_mesh->mNormals[out_mesh->mNumVertices] = (in_mesh->mNormals[index]); + } + + // copy tangents/bi-tangents + if (in_mesh->HasTangentsAndBitangents()) { + out_mesh->mTangents[out_mesh->mNumVertices] = (in_mesh->mTangents[index]); + out_mesh->mBitangents[out_mesh->mNumVertices] = (in_mesh->mBitangents[index]); + } + + // texture coordinates + for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS;++c) { + if (in_mesh->HasTextureCoords( c)) { + out_mesh->mTextureCoords[c][out_mesh->mNumVertices] = in_mesh->mTextureCoords[c][index]; + } + } + // vertex colors + for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_COLOR_SETS;++c) { + if (in_mesh->HasVertexColors( c)) { + out_mesh->mColors[c][out_mesh->mNumVertices] = in_mesh->mColors[c][index]; + } + } + // check whether we have bone weights assigned to this vertex + rFace.mIndices[v] = out_mesh->mNumVertices; + if (avPerVertexWeights) { + VertexWeightTable& table = avPerVertexWeights[ out_mesh->mNumVertices ]; + for (VertexWeightTable::const_iterator iter = table.begin(), end = table.end(); iter != end;++iter) { + // allocate the bone weight array if necessary and store it in the mBones field (HACK!) + BoneWeightList* weight_list = reinterpret_cast(out_mesh->mBones[(*iter).first]); + if (!weight_list) { + weight_list = new BoneWeightList(); + out_mesh->mBones[(*iter).first] = reinterpret_cast(weight_list); + } + weight_list->push_back(aiVertexWeight(out_mesh->mNumVertices,(*iter).second)); + } + } + + was_copied_to[index] = out_mesh->mNumVertices; + out_mesh->mNumVertices++; + } + base++; + if(out_mesh->mNumVertices == out_vertex_index) { + // break here. The face is only added if it was complete + break; + } + } + + // check which bones we'll need to create for this submesh + if (in_mesh->HasBones()) { + aiBone** ppCurrent = out_mesh->mBones; + for (unsigned int k = 0; k < in_mesh->mNumBones;++k) { + // check whether the bone exists + BoneWeightList* const weight_list = reinterpret_cast(out_mesh->mBones[k]); + + if (weight_list) { + const aiBone* const bone_in = in_mesh->mBones[k]; + aiBone* const bone_out = new aiBone(); + *ppCurrent++ = bone_out; + bone_out->mName = aiString(bone_in->mName); + bone_out->mOffsetMatrix =bone_in->mOffsetMatrix; + bone_out->mNumWeights = (unsigned int)weight_list->size(); + bone_out->mWeights = new aiVertexWeight[bone_out->mNumWeights]; + + // copy the vertex weights + ::memcpy(bone_out->mWeights, &(*weight_list)[0],bone_out->mNumWeights * sizeof(aiVertexWeight)); + + delete weight_list; + out_mesh->mNumBones++; + } + } + } + + // copy the face list to the mesh + out_mesh->mFaces = new aiFace[vFaces.size()]; + out_mesh->mNumFaces = (unsigned int)vFaces.size(); + + for (unsigned int p = 0; p < out_mesh->mNumFaces;++p) { + out_mesh->mFaces[p] = vFaces[p]; + } + + // add the newly created mesh to the list + source_mesh_map.push_back(std::make_pair(out_mesh,a)); + + if (base == in_mesh->mNumFaces) { + break; + } + } + + // delete the per-vertex weight list again + delete[] avPerVertexWeights; + + // now delete the old mesh data + delete in_mesh; +} diff --git a/third_party/libassimp/code/Assjson/mesh_splitter.h b/third_party/libassimp/code/Assjson/mesh_splitter.h new file mode 100644 index 0000000000..326f73b41e --- /dev/null +++ b/third_party/libassimp/code/Assjson/mesh_splitter.h @@ -0,0 +1,61 @@ +/* +Assimp2Json +Copyright (c) 2011, Alexander C. Gessler + +Licensed under a 3-clause BSD license. See the LICENSE file for more information. + +*/ + +#ifndef INCLUDED_MESH_SPLITTER +#define INCLUDED_MESH_SPLITTER + +// ---------------------------------------------------------------------------- +// Note: this is largely based on assimp's SplitLargeMeshes_Vertex process. +// it is refactored and the coding style is slightly improved, though. +// ---------------------------------------------------------------------------- + +#include + +struct aiScene; +struct aiMesh; +struct aiNode; + +// --------------------------------------------------------------------------- +/** Splits meshes of unique vertices into meshes with no more vertices than + * a given, configurable threshold value. + */ +class MeshSplitter +{ + +public: + + void SetLimit(unsigned int l) { + LIMIT = l; + } + + unsigned int GetLimit() const { + return LIMIT; + } + +public: + + // ------------------------------------------------------------------- + /** Executes the post processing step on the given imported data. + * At the moment a process is not supposed to fail. + * @param pScene The imported data to work at. + */ + void Execute( aiScene* pScene); + + +private: + + void UpdateNode(aiNode* pcNode, const std::vector >& source_mesh_map); + void SplitMesh (unsigned int index, aiMesh* mesh, std::vector >& source_mesh_map); + +public: + + unsigned int LIMIT; +}; + +#endif // INCLUDED_MESH_SPLITTER + diff --git a/third_party/libassimp/code/AssxmlExporter.cpp b/third_party/libassimp/code/Assxml/AssxmlExporter.cpp similarity index 99% rename from third_party/libassimp/code/AssxmlExporter.cpp rename to third_party/libassimp/code/Assxml/AssxmlExporter.cpp index c9e125d0da..afdecbaf6d 100644 --- a/third_party/libassimp/code/AssxmlExporter.cpp +++ b/third_party/libassimp/code/Assxml/AssxmlExporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -46,13 +46,15 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_EXPORT #ifndef ASSIMP_BUILD_NO_ASSXML_EXPORTER -#include +#include "PostProcessing/ProcessHelper.h" + #include -#include "ProcessHelper.h" #include #include #include +#include + #ifdef ASSIMP_BUILD_NO_OWN_ZLIB # include #else @@ -184,8 +186,13 @@ static std::string encodeXML(const std::string& data) { static void WriteDump(const aiScene* scene, IOStream* io, bool shortened) { time_t tt = ::time( NULL ); - tm* p = ::gmtime( &tt ); - ai_assert( nullptr != p ); +#if _WIN32 + tm* p = gmtime(&tt); +#else + struct tm now; + tm* p = gmtime_r(&tt, &now); +#endif + ai_assert(nullptr != p); // write header std::string header( @@ -550,8 +557,6 @@ void WriteDump(const aiScene* scene, IOStream* io, bool shortened) { mesh->mNormals[n].z); } } - else { - } ioprintf(io,"\t\t\n"); } diff --git a/third_party/libassimp/code/AssxmlExporter.h b/third_party/libassimp/code/Assxml/AssxmlExporter.h similarity index 98% rename from third_party/libassimp/code/AssxmlExporter.h rename to third_party/libassimp/code/Assxml/AssxmlExporter.h index 3db496db2e..8ca887eea0 100644 --- a/third_party/libassimp/code/AssxmlExporter.h +++ b/third_party/libassimp/code/Assxml/AssxmlExporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/B3DImporter.cpp b/third_party/libassimp/code/B3D/B3DImporter.cpp similarity index 99% rename from third_party/libassimp/code/B3DImporter.cpp rename to third_party/libassimp/code/B3D/B3DImporter.cpp index ce8bd5159a..ba484ca000 100644 --- a/third_party/libassimp/code/B3DImporter.cpp +++ b/third_party/libassimp/code/B3D/B3DImporter.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -49,17 +49,19 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_B3D_IMPORTER // internal headers -#include "B3DImporter.h" -#include "TextureTransform.h" -#include "ConvertToLHProcess.h" +#include "B3D/B3DImporter.h" +#include "PostProcessing/TextureTransform.h" +#include "PostProcessing/ConvertToLHProcess.h" + #include -#include #include #include #include #include #include +#include + using namespace Assimp; using namespace std; diff --git a/third_party/libassimp/code/B3DImporter.h b/third_party/libassimp/code/B3D/B3DImporter.h similarity index 99% rename from third_party/libassimp/code/B3DImporter.h rename to third_party/libassimp/code/B3D/B3DImporter.h index 3cb66e5c7b..d52dac34a6 100644 --- a/third_party/libassimp/code/B3DImporter.h +++ b/third_party/libassimp/code/B3D/B3DImporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/BVHLoader.cpp b/third_party/libassimp/code/BVH/BVHLoader.cpp similarity index 99% rename from third_party/libassimp/code/BVHLoader.cpp rename to third_party/libassimp/code/BVH/BVHLoader.cpp index cba58d0561..cd9ab08439 100644 --- a/third_party/libassimp/code/BVHLoader.cpp +++ b/third_party/libassimp/code/BVH/BVHLoader.cpp @@ -4,7 +4,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/BVHLoader.h b/third_party/libassimp/code/BVH/BVHLoader.h similarity index 99% rename from third_party/libassimp/code/BVHLoader.h rename to third_party/libassimp/code/BVH/BVHLoader.h index a18ad81d9e..33b4e24535 100644 --- a/third_party/libassimp/code/BVHLoader.h +++ b/third_party/libassimp/code/BVH/BVHLoader.h @@ -4,7 +4,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/BlenderBMesh.cpp b/third_party/libassimp/code/Blender/BlenderBMesh.cpp similarity index 100% rename from third_party/libassimp/code/BlenderBMesh.cpp rename to third_party/libassimp/code/Blender/BlenderBMesh.cpp diff --git a/third_party/libassimp/code/BlenderBMesh.h b/third_party/libassimp/code/Blender/BlenderBMesh.h similarity index 100% rename from third_party/libassimp/code/BlenderBMesh.h rename to third_party/libassimp/code/Blender/BlenderBMesh.h diff --git a/third_party/libassimp/code/BlenderCustomData.cpp b/third_party/libassimp/code/Blender/BlenderCustomData.cpp similarity index 95% rename from third_party/libassimp/code/BlenderCustomData.cpp rename to third_party/libassimp/code/Blender/BlenderCustomData.cpp index 6821866181..6561eaf224 100644 --- a/third_party/libassimp/code/BlenderCustomData.cpp +++ b/third_party/libassimp/code/Blender/BlenderCustomData.cpp @@ -28,7 +28,11 @@ namespace Assimp { #define IMPL_STRUCT_READ(ty) \ bool read##ty(ElemBase *v, const size_t cnt, const FileDatabase &db) { \ - return read(db.dna[#ty], dynamic_cast(v), cnt, db); \ + ty *ptr = dynamic_cast(v); \ + if (nullptr == ptr) { \ + return false; \ + } \ + return read(db.dna[#ty], ptr, cnt, db); \ } #define IMPL_STRUCT_CREATE(ty) \ diff --git a/third_party/libassimp/code/BlenderCustomData.h b/third_party/libassimp/code/Blender/BlenderCustomData.h similarity index 100% rename from third_party/libassimp/code/BlenderCustomData.h rename to third_party/libassimp/code/Blender/BlenderCustomData.h diff --git a/third_party/libassimp/code/BlenderDNA.cpp b/third_party/libassimp/code/Blender/BlenderDNA.cpp similarity index 99% rename from third_party/libassimp/code/BlenderDNA.cpp rename to third_party/libassimp/code/Blender/BlenderDNA.cpp index f84c456016..f274e02f90 100644 --- a/third_party/libassimp/code/BlenderDNA.cpp +++ b/third_party/libassimp/code/Blender/BlenderDNA.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/BlenderDNA.h b/third_party/libassimp/code/Blender/BlenderDNA.h similarity index 99% rename from third_party/libassimp/code/BlenderDNA.h rename to third_party/libassimp/code/Blender/BlenderDNA.h index ecf606a3b6..375d0c4bf7 100644 --- a/third_party/libassimp/code/BlenderDNA.h +++ b/third_party/libassimp/code/Blender/BlenderDNA.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -416,7 +416,7 @@ template <> struct Structure :: _defaultInitializer { void operator ()(T& /*out*/,const char* = "") { // obviously, it is crucial that _DefaultInitializer is used // only from within a catch clause. - throw; + throw DeadlyImportError("Constructing BlenderDNA Structure encountered an error"); } }; diff --git a/third_party/libassimp/code/BlenderDNA.inl b/third_party/libassimp/code/Blender/BlenderDNA.inl similarity index 99% rename from third_party/libassimp/code/BlenderDNA.inl rename to third_party/libassimp/code/Blender/BlenderDNA.inl index 89c94e7bf9..65bc1374c5 100644 --- a/third_party/libassimp/code/BlenderDNA.inl +++ b/third_party/libassimp/code/Blender/BlenderDNA.inl @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/BlenderIntermediate.h b/third_party/libassimp/code/Blender/BlenderIntermediate.h similarity index 99% rename from third_party/libassimp/code/BlenderIntermediate.h rename to third_party/libassimp/code/Blender/BlenderIntermediate.h index f3d34d1b2f..95fdf0f03a 100644 --- a/third_party/libassimp/code/BlenderIntermediate.h +++ b/third_party/libassimp/code/Blender/BlenderIntermediate.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/BlenderLoader.cpp b/third_party/libassimp/code/Blender/BlenderLoader.cpp similarity index 97% rename from third_party/libassimp/code/BlenderLoader.cpp rename to third_party/libassimp/code/Blender/BlenderLoader.cpp index b0d273a5f1..d39cb96991 100644 --- a/third_party/libassimp/code/BlenderLoader.cpp +++ b/third_party/libassimp/code/Blender/BlenderLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -1225,6 +1225,16 @@ aiLight* BlenderImporter::ConvertLight(const Scene& /*in*/, const Object* obj, c case Lamp::Type_Local: out->mType = aiLightSource_POINT; break; + case Lamp::Type_Spot: + out->mType = aiLightSource_SPOT; + + // blender orients directional lights as facing toward -z + out->mDirection = aiVector3D(0.f, 0.f, -1.f); + out->mUp = aiVector3D(0.f, 1.f, 0.f); + + out->mAngleInnerCone = lamp->spotsize * (1.0f - lamp->spotblend); + out->mAngleOuterCone = lamp->spotsize; + break; case Lamp::Type_Sun: out->mType = aiLightSource_DIRECTIONAL; @@ -1255,6 +1265,23 @@ aiLight* BlenderImporter::ConvertLight(const Scene& /*in*/, const Object* obj, c out->mColorAmbient = aiColor3D(lamp->r, lamp->g, lamp->b) * lamp->energy; out->mColorSpecular = aiColor3D(lamp->r, lamp->g, lamp->b) * lamp->energy; out->mColorDiffuse = aiColor3D(lamp->r, lamp->g, lamp->b) * lamp->energy; + + // If default values are supplied, compute the coefficients from light's max distance + // Read this: https://imdoingitwrong.wordpress.com/2011/01/31/light-attenuation/ + // + if (lamp->constant_coefficient == 1.0f && lamp->linear_coefficient == 0.0f && lamp->quadratic_coefficient == 0.0f && lamp->dist > 0.0f) + { + out->mAttenuationConstant = 1.0f; + out->mAttenuationLinear = 2.0f / lamp->dist; + out->mAttenuationQuadratic = 1.0f / (lamp->dist * lamp->dist); + } + else + { + out->mAttenuationConstant = lamp->constant_coefficient; + out->mAttenuationLinear = lamp->linear_coefficient; + out->mAttenuationQuadratic = lamp->quadratic_coefficient; + } + return out.release(); } diff --git a/third_party/libassimp/code/BlenderLoader.h b/third_party/libassimp/code/Blender/BlenderLoader.h similarity index 99% rename from third_party/libassimp/code/BlenderLoader.h rename to third_party/libassimp/code/Blender/BlenderLoader.h index 9f452a0aab..d85a828429 100644 --- a/third_party/libassimp/code/BlenderLoader.h +++ b/third_party/libassimp/code/Blender/BlenderLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/BlenderModifier.cpp b/third_party/libassimp/code/Blender/BlenderModifier.cpp similarity index 99% rename from third_party/libassimp/code/BlenderModifier.cpp rename to third_party/libassimp/code/Blender/BlenderModifier.cpp index 1f32ee410e..cc7acc9295 100644 --- a/third_party/libassimp/code/BlenderModifier.cpp +++ b/third_party/libassimp/code/Blender/BlenderModifier.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/BlenderModifier.h b/third_party/libassimp/code/Blender/BlenderModifier.h similarity index 99% rename from third_party/libassimp/code/BlenderModifier.h rename to third_party/libassimp/code/Blender/BlenderModifier.h index b8797691ba..c260ba1f6d 100644 --- a/third_party/libassimp/code/BlenderModifier.h +++ b/third_party/libassimp/code/Blender/BlenderModifier.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/BlenderScene.cpp b/third_party/libassimp/code/Blender/BlenderScene.cpp similarity index 99% rename from third_party/libassimp/code/BlenderScene.cpp rename to third_party/libassimp/code/Blender/BlenderScene.cpp index 4fc353b15c..39c2793d55 100644 --- a/third_party/libassimp/code/BlenderScene.cpp +++ b/third_party/libassimp/code/Blender/BlenderScene.cpp @@ -211,9 +211,12 @@ template <> void Structure :: Convert ( ReadField(dest.b,"b",db); ReadField(dest.k,"k",db); ReadField(dest.energy,"energy",db); - ReadField(dest.dist,"dist",db); + ReadField(dest.dist,"dist",db); ReadField(dest.spotsize,"spotsize",db); ReadField(dest.spotblend,"spotblend",db); + ReadField(dest.constant_coefficient, "coeff_const", db); + ReadField(dest.linear_coefficient, "coeff_lin", db); + ReadField(dest.quadratic_coefficient, "coeff_quad", db); ReadField(dest.att1,"att1",db); ReadField(dest.att2,"att2",db); ReadField(temp,"falloff_type",db); diff --git a/third_party/libassimp/code/BlenderScene.h b/third_party/libassimp/code/Blender/BlenderScene.h similarity index 99% rename from third_party/libassimp/code/BlenderScene.h rename to third_party/libassimp/code/Blender/BlenderScene.h index b74d7b1981..dd3f1444cb 100644 --- a/third_party/libassimp/code/BlenderScene.h +++ b/third_party/libassimp/code/Blender/BlenderScene.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -538,6 +538,10 @@ struct Lamp : ElemBase { float energy, dist, spotsize, spotblend; //float haint; + float constant_coefficient; + float linear_coefficient; + float quadratic_coefficient; + float att1, att2; //struct CurveMapping *curfalloff; FalloffType falloff_type; diff --git a/third_party/libassimp/code/BlenderSceneGen.h b/third_party/libassimp/code/Blender/BlenderSceneGen.h similarity index 100% rename from third_party/libassimp/code/BlenderSceneGen.h rename to third_party/libassimp/code/Blender/BlenderSceneGen.h diff --git a/third_party/libassimp/code/BlenderTessellator.cpp b/third_party/libassimp/code/Blender/BlenderTessellator.cpp similarity index 99% rename from third_party/libassimp/code/BlenderTessellator.cpp rename to third_party/libassimp/code/Blender/BlenderTessellator.cpp index afedbfb539..d98c2e865d 100644 --- a/third_party/libassimp/code/BlenderTessellator.cpp +++ b/third_party/libassimp/code/Blender/BlenderTessellator.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/BlenderTessellator.h b/third_party/libassimp/code/Blender/BlenderTessellator.h similarity index 97% rename from third_party/libassimp/code/BlenderTessellator.h rename to third_party/libassimp/code/Blender/BlenderTessellator.h index dab3ba8aa0..518e56c72e 100644 --- a/third_party/libassimp/code/BlenderTessellator.h +++ b/third_party/libassimp/code/Blender/BlenderTessellator.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -144,7 +144,11 @@ namespace Assimp #if ASSIMP_BLEND_WITH_POLY_2_TRI -#include "../contrib/poly2tri/poly2tri/poly2tri.h" +#ifdef ASSIMP_USE_HUNTER +# include +#else +# include "../contrib/poly2tri/poly2tri/poly2tri.h" +#endif namespace Assimp { diff --git a/third_party/libassimp/code/C4DImporter.cpp b/third_party/libassimp/code/C4D/C4DImporter.cpp similarity index 89% rename from third_party/libassimp/code/C4DImporter.cpp rename to third_party/libassimp/code/C4D/C4DImporter.cpp index 665d746334..6e5b7d39b1 100644 --- a/third_party/libassimp/code/C4DImporter.cpp +++ b/third_party/libassimp/code/C4D/C4DImporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2012, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, @@ -68,8 +68,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using namespace melange; // overload this function and fill in your own unique data -void GetWriterInfo(int &id, String &appname) -{ +void GetWriterInfo(int &id, String &appname) { id = 2424226; appname = "Open Asset Import Library"; } @@ -78,7 +77,10 @@ using namespace Assimp; using namespace Assimp::Formatter; namespace Assimp { - template<> const std::string LogFunctions::log_prefix = "C4D: "; + template<> const char* LogFunctions::Prefix() { + static auto prefix = "C4D: "; + return prefix; + } } static const aiImporterDesc desc = { @@ -97,47 +99,44 @@ static const aiImporterDesc desc = { // ------------------------------------------------------------------------------------------------ C4DImporter::C4DImporter() -{} +: BaseImporter() { + // empty +} // ------------------------------------------------------------------------------------------------ -C4DImporter::~C4DImporter() -{} +C4DImporter::~C4DImporter() { + // empty +} // ------------------------------------------------------------------------------------------------ -bool C4DImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const -{ +bool C4DImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const { const std::string& extension = GetExtension(pFile); if (extension == "c4d") { return true; - } - - else if ((!extension.length() || checkSig) && pIOHandler) { + } else if ((!extension.length() || checkSig) && pIOHandler) { // TODO } + return false; } // ------------------------------------------------------------------------------------------------ -const aiImporterDesc* C4DImporter::GetInfo () const -{ +const aiImporterDesc* C4DImporter::GetInfo () const { return &desc; } // ------------------------------------------------------------------------------------------------ -void C4DImporter::SetupProperties(const Importer* /*pImp*/) -{ +void C4DImporter::SetupProperties(const Importer* /*pImp*/) { // nothing to be done for the moment } // ------------------------------------------------------------------------------------------------ // Imports the given file into the given scene structure. -void C4DImporter::InternReadFile( const std::string& pFile, - aiScene* pScene, IOSystem* pIOHandler) -{ +void C4DImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) { std::unique_ptr file( pIOHandler->Open( pFile)); - if( file.get() == NULL) { + if( file.get() == nullptr ) { ThrowException("failed to open file " + pFile); } @@ -151,7 +150,7 @@ void C4DImporter::InternReadFile( const std::string& pFile, // open document first BaseDocument* doc = LoadDocument(f, SCENEFILTER_OBJECTS | SCENEFILTER_MATERIALS); - if(doc == NULL) { + if(doc == nullptr ) { ThrowException("failed to read document " + pFile); } @@ -160,11 +159,10 @@ void C4DImporter::InternReadFile( const std::string& pFile, // first convert all materials ReadMaterials(doc->GetFirstMaterial()); - // process C4D scenegraph recursively + // process C4D scene-graph recursively try { RecurseHierarchy(doc->GetFirstObject(), pScene->mRootNode); - } - catch(...) { + } catch(...) { for(aiMesh* mesh : meshes) { delete mesh; } @@ -201,8 +199,7 @@ void C4DImporter::InternReadFile( const std::string& pFile, // ------------------------------------------------------------------------------------------------ -bool C4DImporter::ReadShader(aiMaterial* out, melange::BaseShader* shader) -{ +bool C4DImporter::ReadShader(aiMaterial* out, melange::BaseShader* shader) { // based on Melange sample code (C4DImportExport.cpp) while(shader) { if(shader->GetType() == Xlayer) { @@ -220,15 +217,12 @@ bool C4DImporter::ReadShader(aiMaterial* out, melange::BaseShader* shader) // Ignore the actual layer blending - models for real-time rendering should not // use them in a non-trivial way. Just try to find textures that we can apply // to the model. - while (lsl) - { - if (lsl->GetType() == TypeFolder) - { + while (lsl) { + if (lsl->GetType() == TypeFolder) { BlendFolder* const folder = dynamic_cast(lsl); LayerShaderLayer *subLsl = dynamic_cast(folder->m_Children.GetObject(0)); - while (subLsl) - { + while (subLsl) { if (subLsl->GetType() == TypeShader) { BlendShader* const shader = dynamic_cast(subLsl); if(ReadShader(out, static_cast(shader->m_pLink->GetLink()))) { @@ -238,8 +232,7 @@ bool C4DImporter::ReadShader(aiMaterial* out, melange::BaseShader* shader) subLsl = subLsl->GetNext(); } - } - else if (lsl->GetType() == TypeShader) { + } else if (lsl->GetType() == TypeShader) { BlendShader* const shader = dynamic_cast(lsl); if(ReadShader(out, static_cast(shader->m_pLink->GetLink()))) { return true; @@ -248,33 +241,27 @@ bool C4DImporter::ReadShader(aiMaterial* out, melange::BaseShader* shader) lsl = lsl->GetNext(); } - } - else if ( shader->GetType() == Xbitmap ) - { + } else if ( shader->GetType() == Xbitmap ) { aiString path; shader->GetFileName().GetString().GetCString(path.data, MAXLEN-1); path.length = ::strlen(path.data); out->AddProperty(&path, AI_MATKEY_TEXTURE_DIFFUSE(0)); return true; - } - else { + } else { LogWarn("ignoring shader type: " + std::string(GetObjectTypeName(shader->GetType()))); } shader = shader->GetNext(); } + return false; } - // ------------------------------------------------------------------------------------------------ -void C4DImporter::ReadMaterials(melange::BaseMaterial* mat) -{ +void C4DImporter::ReadMaterials(melange::BaseMaterial* mat) { // based on Melange sample code - while (mat) - { + while (mat) { const String& name = mat->GetName(); - if (mat->GetType() == Mmaterial) - { + if (mat->GetType() == Mmaterial) { aiMaterial* out = new aiMaterial(); material_mapping[mat] = static_cast(materials.size()); materials.push_back(out); @@ -286,8 +273,7 @@ void C4DImporter::ReadMaterials(melange::BaseMaterial* mat) Material& m = dynamic_cast(*mat); - if (m.GetChannelState(CHANNEL_COLOR)) - { + if (m.GetChannelState(CHANNEL_COLOR)) { GeData data; mat->GetParameter(MATERIAL_COLOR_COLOR, data); Vector color = data.GetVector(); @@ -307,9 +293,7 @@ void C4DImporter::ReadMaterials(melange::BaseMaterial* mat) if(shader) { ReadShader(out, shader); } - } - else - { + } else { LogWarn("ignoring plugin material: " + std::string(GetObjectTypeName(mat->GetType()))); } mat = mat->GetNext(); @@ -317,14 +301,12 @@ void C4DImporter::ReadMaterials(melange::BaseMaterial* mat) } // ------------------------------------------------------------------------------------------------ -void C4DImporter::RecurseHierarchy(BaseObject* object, aiNode* parent) -{ - ai_assert(parent != NULL); +void C4DImporter::RecurseHierarchy(BaseObject* object, aiNode* parent) { + ai_assert(parent != nullptr ); std::vector nodes; // based on Melange sample code - while (object) - { + while (object) { const String& name = object->GetName(); const LONG type = object->GetType(); const Matrix& ml = object->GetMl(); @@ -356,26 +338,20 @@ void C4DImporter::RecurseHierarchy(BaseObject* object, aiNode* parent) nodes.push_back(nd); GeData data; - if (type == Ocamera) - { + if (type == Ocamera) { object->GetParameter(CAMERAOBJECT_FOV, data); // TODO: read camera - } - else if (type == Olight) - { + } else if (type == Olight) { // TODO: read light - } - else if (type == Opolygon) - { + } else if (type == Opolygon) { aiMesh* const mesh = ReadMesh(object); - if(mesh != NULL) { + if(mesh != nullptr) { nd->mNumMeshes = 1; nd->mMeshes = new unsigned int[1]; nd->mMeshes[0] = static_cast(meshes.size()); meshes.push_back(mesh); } - } - else { + } else { LogWarn("ignoring object: " + std::string(GetObjectTypeName(type))); } @@ -389,28 +365,27 @@ void C4DImporter::RecurseHierarchy(BaseObject* object, aiNode* parent) std::copy(nodes.begin(), nodes.end(), parent->mChildren); } - // ------------------------------------------------------------------------------------------------ -aiMesh* C4DImporter::ReadMesh(BaseObject* object) -{ - ai_assert(object != NULL && object->GetType() == Opolygon); +aiMesh* C4DImporter::ReadMesh(BaseObject* object) { + ai_assert(object != nullptr); + ai_assert( object->GetType() == Opolygon ); // based on Melange sample code PolygonObject* const polyObject = dynamic_cast(object); - ai_assert(polyObject != NULL); + ai_assert(polyObject != nullptr); const LONG pointCount = polyObject->GetPointCount(); const LONG polyCount = polyObject->GetPolygonCount(); if(!polyObject || !pointCount) { LogWarn("ignoring mesh with zero vertices or faces"); - return NULL; + return nullptr; } const Vector* points = polyObject->GetPointR(); - ai_assert(points != NULL); + ai_assert(points != nullptr); const CPolygon* polys = polyObject->GetPolygonR(); - ai_assert(polys != NULL); + ai_assert(polys != nullptr); std::unique_ptr mesh(new aiMesh()); mesh->mNumFaces = static_cast(polyCount); @@ -443,14 +418,14 @@ aiMesh* C4DImporter::ReadMesh(BaseObject* object) // check if there are normals, tangents or UVW coordinates BaseTag* tag = object->GetTag(Tnormal); - NormalTag* normals_src = NULL; + NormalTag* normals_src = nullptr; if(tag) { normals_src = dynamic_cast(tag); normals = mesh->mNormals = new aiVector3D[mesh->mNumVertices](); } tag = object->GetTag(Ttangent); - TangentTag* tangents_src = NULL; + TangentTag* tangents_src = nullptr; if(tag) { tangents_src = dynamic_cast(tag); tangents = mesh->mTangents = new aiVector3D[mesh->mNumVertices](); @@ -458,15 +433,14 @@ aiMesh* C4DImporter::ReadMesh(BaseObject* object) } tag = object->GetTag(Tuvw); - UVWTag* uvs_src = NULL; + UVWTag* uvs_src = nullptr; if(tag) { uvs_src = dynamic_cast(tag); uvs = mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices](); } // copy vertices and extra channels over and populate faces - for (LONG i = 0; i < polyCount; ++i, ++face) - { + for (LONG i = 0; i < polyCount; ++i, ++face) { ai_assert(polys[i].a < pointCount && polys[i].a >= 0); const Vector& pointA = points[polys[i].a]; verts->x = pointA.x; @@ -489,8 +463,7 @@ aiMesh* C4DImporter::ReadMesh(BaseObject* object) ++verts; // TODO: do we also need to handle lines or points with similar checks? - if (polys[i].c != polys[i].d) - { + if (polys[i].c != polys[i].d) { ai_assert(polys[i].d < pointCount && polys[i].d >= 0); face->mNumIndices = 4; @@ -500,8 +473,7 @@ aiMesh* C4DImporter::ReadMesh(BaseObject* object) verts->y = pointD.y; verts->z = pointD.z; ++verts; - } - else { + } else { face->mNumIndices = 3; } face->mIndices = new unsigned int[face->mNumIndices]; @@ -513,8 +485,7 @@ aiMesh* C4DImporter::ReadMesh(BaseObject* object) if (normals_src) { if(i >= normals_src->GetDataCount()) { LogError("unexpected number of normals, ignoring"); - } - else { + } else { ConstNormalHandle normal_handle = normals_src->GetDataAddressR(); NormalStruct nor; NormalTag::Get(normal_handle, i, nor); @@ -616,26 +587,25 @@ aiMesh* C4DImporter::ReadMesh(BaseObject* object) } mesh->mMaterialIndex = ResolveMaterial(polyObject); + return mesh.release(); } - // ------------------------------------------------------------------------------------------------ -unsigned int C4DImporter::ResolveMaterial(PolygonObject* obj) -{ - ai_assert(obj != NULL); +unsigned int C4DImporter::ResolveMaterial(PolygonObject* obj) { + ai_assert(obj != nullptr); const unsigned int mat_count = static_cast(materials.size()); BaseTag* tag = obj->GetTag(Ttexture); - if(tag == NULL) { + if(tag == nullptr) { return mat_count; } TextureTag& ttag = dynamic_cast(*tag); BaseMaterial* const mat = ttag.GetMaterial(); - ai_assert(mat != NULL); + ai_assert(mat != nullptr); const MaterialMap::const_iterator it = material_mapping.find(mat); if(it == material_mapping.end()) { @@ -643,6 +613,7 @@ unsigned int C4DImporter::ResolveMaterial(PolygonObject* obj) } ai_assert((*it).second < mat_count); + return (*it).second; } diff --git a/third_party/libassimp/code/C4DImporter.h b/third_party/libassimp/code/C4D/C4DImporter.h similarity index 97% rename from third_party/libassimp/code/C4DImporter.h rename to third_party/libassimp/code/C4D/C4DImporter.h index 2f67d90f34..f3b1351f6d 100644 --- a/third_party/libassimp/code/C4DImporter.h +++ b/third_party/libassimp/code/C4D/C4DImporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2012, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, @@ -48,6 +48,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include + +// Forward declarations struct aiNode; struct aiMesh; struct aiMaterial; @@ -61,8 +63,7 @@ namespace melange { class BaseShader; } -namespace Assimp { - +namespace Assimp { // TinyFormatter.h namespace Formatter { template class basic_formatter; @@ -75,17 +76,10 @@ namespace Assimp { * * Note that Melange is not free software. */ // ------------------------------------------------------------------------------------------- -class C4DImporter : public BaseImporter, public LogFunctions -{ +class C4DImporter : public BaseImporter, public LogFunctions { public: - C4DImporter(); ~C4DImporter(); - - -public: - - // -------------------- bool CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const; @@ -119,5 +113,5 @@ private: }; // !class C4DImporter } // end of namespace Assimp -#endif // INCLUDED_AI_CINEMA_4D_LOADER_H +#endif // INCLUDED_AI_CINEMA_4D_LOADER_H diff --git a/third_party/libassimp/code/AssimpCExport.cpp b/third_party/libassimp/code/CApi/AssimpCExport.cpp similarity index 98% rename from third_party/libassimp/code/AssimpCExport.cpp rename to third_party/libassimp/code/CApi/AssimpCExport.cpp index caf51a08c0..7557edcfc6 100644 --- a/third_party/libassimp/code/AssimpCExport.cpp +++ b/third_party/libassimp/code/CApi/AssimpCExport.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -49,7 +49,7 @@ Assimp C export interface. See Exporter.cpp for some notes. #include "CInterfaceIOWrapper.h" #include -#include "ScenePrivate.h" +#include "Common/ScenePrivate.h" #include using namespace Assimp; @@ -60,7 +60,6 @@ ASSIMP_API size_t aiGetExportFormatCount(void) return Exporter().GetExportFormatCount(); } - // ------------------------------------------------------------------------------------------------ ASSIMP_API const aiExportFormatDesc* aiGetExportFormatDescription( size_t index) { diff --git a/third_party/libassimp/code/CInterfaceIOWrapper.cpp b/third_party/libassimp/code/CApi/CInterfaceIOWrapper.cpp similarity index 99% rename from third_party/libassimp/code/CInterfaceIOWrapper.cpp rename to third_party/libassimp/code/CApi/CInterfaceIOWrapper.cpp index 41dbba7727..5a3a49565a 100644 --- a/third_party/libassimp/code/CInterfaceIOWrapper.cpp +++ b/third_party/libassimp/code/CApi/CInterfaceIOWrapper.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/CInterfaceIOWrapper.h b/third_party/libassimp/code/CApi/CInterfaceIOWrapper.h similarity index 98% rename from third_party/libassimp/code/CInterfaceIOWrapper.h rename to third_party/libassimp/code/CApi/CInterfaceIOWrapper.h index 6f0eb79571..2162320302 100644 --- a/third_party/libassimp/code/CInterfaceIOWrapper.h +++ b/third_party/libassimp/code/CApi/CInterfaceIOWrapper.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/CMakeLists.txt b/third_party/libassimp/code/CMakeLists.txt index 6b8d3d3227..55538d9650 100644 --- a/third_party/libassimp/code/CMakeLists.txt +++ b/third_party/libassimp/code/CMakeLists.txt @@ -1,9 +1,8 @@ # Open Asset Import Library (assimp) # ---------------------------------------------------------------------- # -# Copyright (c) 2006-2018, assimp team - - +# Copyright (c) 2006-2019, assimp team +# # All rights reserved. # # Redistribution and use of this software in source and binary forms, @@ -44,9 +43,14 @@ # 3) Add libassimp using the file lists (eliminates duplication of file names between # source groups and library command) # -cmake_minimum_required( VERSION 2.6 ) +cmake_minimum_required( VERSION 3.0 ) SET( HEADER_PATH ../include/assimp ) +if(NOT ANDROID AND ASSIMP_ANDROID_JNIIOSYSTEM) + message(WARNING "Requesting Android JNI I/O-System in non-Android toolchain. Resetting ASSIMP_ANDROID_JNIIOSYSTEM to OFF.") + set(ASSIMP_ANDROID_JNIIOSYSTEM OFF) +endif(NOT ANDROID AND ASSIMP_ANDROID_JNIIOSYSTEM) + SET( COMPILER_HEADERS ${HEADER_PATH}/Compiler/pushpack1.h ${HEADER_PATH}/Compiler/poppack1.h @@ -56,6 +60,7 @@ SOURCE_GROUP( Compiler FILES ${COMPILER_HEADERS}) SET( PUBLIC_HEADERS ${HEADER_PATH}/anim.h + ${HEADER_PATH}/aabb.h ${HEADER_PATH}/ai_assert.h ${HEADER_PATH}/camera.h ${HEADER_PATH}/color4.h @@ -99,6 +104,7 @@ SET( PUBLIC_HEADERS ${HEADER_PATH}/Exporter.hpp ${HEADER_PATH}/DefaultIOStream.h ${HEADER_PATH}/DefaultIOSystem.h + ${HEADER_PATH}/ZipArchiveIOSystem.h ${HEADER_PATH}/SceneCombiner.h ${HEADER_PATH}/fast_atof.h ${HEADER_PATH}/qnan.h @@ -137,60 +143,70 @@ SET( PUBLIC_HEADERS ) SET( Core_SRCS - Assimp.cpp + Common/Assimp.cpp ) +IF(MSVC) + list(APPEND Core_SRCS "res/assimp.rc") +ENDIF(MSVC) + SET( Logging_SRCS ${HEADER_PATH}/DefaultLogger.hpp ${HEADER_PATH}/LogStream.hpp ${HEADER_PATH}/Logger.hpp ${HEADER_PATH}/NullLogger.hpp - Win32DebugLogStream.h - DefaultLogger.cpp - FileLogStream.h - StdOStreamLogStream.h + Common/Win32DebugLogStream.h + Common/DefaultLogger.cpp + Common/FileLogStream.h + Common/StdOStreamLogStream.h ) SOURCE_GROUP(Logging FILES ${Logging_SRCS}) SET( Common_SRCS - BaseImporter.cpp - BaseProcess.cpp - BaseProcess.h - Importer.h - ScenePrivate.h - PostStepRegistry.cpp - ImporterRegistry.cpp - DefaultProgressHandler.h - DefaultIOStream.cpp - DefaultIOSystem.cpp - CInterfaceIOWrapper.cpp - CInterfaceIOWrapper.h - Importer.cpp - IFF.h - SGSpatialSort.cpp - VertexTriangleAdjacency.cpp - VertexTriangleAdjacency.h - SpatialSort.cpp - SceneCombiner.cpp - ScenePreprocessor.cpp - ScenePreprocessor.h - SkeletonMeshBuilder.cpp - SplitByBoneCountProcess.cpp - SplitByBoneCountProcess.h - StandardShapes.cpp - TargetAnimation.cpp - TargetAnimation.h - RemoveComments.cpp - Subdivision.cpp - scene.cpp - Bitmap.cpp - Version.cpp - CreateAnimMesh.cpp - simd.h - simd.cpp + Common/BaseImporter.cpp + Common/BaseProcess.cpp + Common/BaseProcess.h + Common/Importer.h + Common/ScenePrivate.h + Common/PostStepRegistry.cpp + Common/ImporterRegistry.cpp + Common/DefaultProgressHandler.h + Common/DefaultIOStream.cpp + Common/DefaultIOSystem.cpp + Common/ZipArchiveIOSystem.cpp + Common/PolyTools.h + Common/Importer.cpp + Common/IFF.h + Common/SGSpatialSort.cpp + Common/VertexTriangleAdjacency.cpp + Common/VertexTriangleAdjacency.h + Common/SpatialSort.cpp + Common/SceneCombiner.cpp + Common/ScenePreprocessor.cpp + Common/ScenePreprocessor.h + Common/SkeletonMeshBuilder.cpp + Common/SplitByBoneCountProcess.cpp + Common/SplitByBoneCountProcess.h + Common/StandardShapes.cpp + Common/TargetAnimation.cpp + Common/TargetAnimation.h + Common/RemoveComments.cpp + Common/Subdivision.cpp + Common/scene.cpp + Common/Bitmap.cpp + Common/Version.cpp + Common/CreateAnimMesh.cpp + Common/simd.h + Common/simd.cpp ) SOURCE_GROUP(Common FILES ${Common_SRCS}) +SET( CApi_SRCS + CApi/CInterfaceIOWrapper.cpp + CApi/CInterfaceIOWrapper.h +) +SOURCE_GROUP(CApi FILES ${CApi_SRCS}) + SET( STEPParser_SRCS Importer/STEPParser/STEPFileReader.h Importer/STEPParser/STEPFileReader.cpp @@ -201,8 +217,8 @@ SOURCE_GROUP(STEPParser FILES ${STEPParser_SRCS}) IF ( ASSIMP_BUILD_NONFREE_C4D_IMPORTER ) SET( C4D_SRCS - C4DImporter.cpp - C4DImporter.h + C4D/C4DImporter.cpp + C4D/C4DImporter.h ) SOURCE_GROUP( C4D FILES ${C4D_SRCS}) ENDIF ( ASSIMP_BUILD_NONFREE_C4D_IMPORTER ) @@ -211,7 +227,7 @@ ENDIF ( ASSIMP_BUILD_NONFREE_C4D_IMPORTER ) # 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) +OPTION(ASSIMP_BUILD_ALL_IMPORTERS_BY_DEFAULT "default value of all ASSIMP_BUILD_XXX_IMPORTER values" TRUE) # macro to add the CMake Option ADD_ASSIMP_IMPORTER_ which enables compile of loader # this way selective loaders can be compiled (reduces filesize + compile time) @@ -227,258 +243,308 @@ MACRO(ADD_ASSIMP_IMPORTER name) IF (ASSIMP_IMPORTER_ENABLED) LIST(APPEND ASSIMP_LOADER_SRCS ${ARGN}) SET(ASSIMP_IMPORTERS_ENABLED "${ASSIMP_IMPORTERS_ENABLED} ${name}") - SET(${name}_SRCS ${ARGN}) SOURCE_GROUP(${name} FILES ${ARGN}) ELSE() SET(${name}_SRC "") SET(ASSIMP_IMPORTERS_DISABLED "${ASSIMP_IMPORTERS_DISABLED} ${name}") add_definitions(-DASSIMP_BUILD_NO_${name}_IMPORTER) + ENDIF() +ENDMACRO() + +# if this variable is set to TRUE, the user can manually disable exporters by setting +# ASSIMP_BUILD_XXX_EXPORTER to FALSE for each exporter +# if this variable is set to FALSE, the user can manually enable exporters by setting +# ASSIMP_BUILD_XXX_EXPORTER to TRUE for each exporter +OPTION(ASSIMP_BUILD_ALL_EXPORTERS_BY_DEFAULT "default value of all ASSIMP_BUILD_XXX_EXPORTER values" TRUE) + +# macro to add the CMake Option ADD_ASSIMP_IMPORTER_ which enables compile of loader +# this way selective loaders can be compiled (reduces filesize + compile time) +MACRO(ADD_ASSIMP_EXPORTER name) + IF (ASSIMP_NO_EXPORT) + set(ASSIMP_EXPORTER_ENABLED FALSE) + ELSEIF (ASSIMP_BUILD_ALL_EXPORTERS_BY_DEFAULT) + set(ASSIMP_EXPORTER_ENABLED TRUE) + IF (DEFINED ASSIMP_BUILD_${name}_EXPORTER AND NOT ASSIMP_BUILD_${name}_EXPORTER) + set(ASSIMP_EXPORTER_ENABLED FALSE) + ENDIF () + ELSE () + set(ASSIMP_EXPORTER_ENABLED ${ASSIMP_BUILD_${name}_EXPORTER}) + ENDIF () + + IF (ASSIMP_EXPORTER_ENABLED) + SET(ASSIMP_EXPORTERS_ENABLED "${ASSIMP_EXPORTERS_ENABLED} ${name}") + LIST(APPEND ASSIMP_EXPORTER_SRCS ${ARGN}) + SOURCE_GROUP(${name}_EXPORTER FILES ${ARGN}) + ELSE() + SET(ASSIMP_EXPORTERS_DISABLED "${ASSIMP_EXPORTERS_DISABLED} ${name}") add_definitions(-DASSIMP_BUILD_NO_${name}_EXPORTER) ENDIF() ENDMACRO() SET(ASSIMP_LOADER_SRCS "") SET(ASSIMP_IMPORTERS_ENABLED "") # list of enabled importers -SET(ASSIMP_IMPORTERS_DISABLED "") # disabled list (used to print) +SET(ASSIMP_IMPORTERS_DISABLED "") # disabled importers list (used to print) + +SET(ASSIMP_EXPORTER_SRCS "") +SET(ASSIMP_EXPORTERS_ENABLED "") # list of enabled exporters +SET(ASSIMP_EXPORTERS_DISABLED "") # disabled exporters 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 + AMF/AMFImporter.hpp + AMF/AMFImporter_Macro.hpp + AMF/AMFImporter_Node.hpp + AMF/AMFImporter.cpp + AMF/AMFImporter_Geometry.cpp + AMF/AMFImporter_Material.cpp + AMF/AMFImporter_Postprocess.cpp ) ADD_ASSIMP_IMPORTER( 3DS - 3DSConverter.cpp - 3DSHelper.h - 3DSLoader.cpp - 3DSLoader.h - 3DSExporter.h - 3DSExporter.cpp + 3DS/3DSConverter.cpp + 3DS/3DSHelper.h + 3DS/3DSLoader.cpp + 3DS/3DSLoader.h +) + +ADD_ASSIMP_EXPORTER( 3DS + 3DS/3DSExporter.h + 3DS/3DSExporter.cpp ) ADD_ASSIMP_IMPORTER( AC - ACLoader.cpp - ACLoader.h + AC/ACLoader.cpp + AC/ACLoader.h ) ADD_ASSIMP_IMPORTER( ASE - ASELoader.cpp - ASELoader.h - ASEParser.cpp - ASEParser.h + ASE/ASELoader.cpp + ASE/ASELoader.h + ASE/ASEParser.cpp + ASE/ASEParser.h ) ADD_ASSIMP_IMPORTER( ASSBIN - AssbinExporter.h - AssbinExporter.cpp - AssbinLoader.h - AssbinLoader.cpp + Assbin/AssbinLoader.h + Assbin/AssbinLoader.cpp ) -ADD_ASSIMP_IMPORTER( ASSXML - AssxmlExporter.h - AssxmlExporter.cpp +ADD_ASSIMP_EXPORTER( ASSBIN + Assbin/AssbinExporter.h + Assbin/AssbinExporter.cpp +) + +ADD_ASSIMP_EXPORTER( ASSXML + Assxml/AssxmlExporter.h + Assxml/AssxmlExporter.cpp ) ADD_ASSIMP_IMPORTER( B3D - B3DImporter.cpp - B3DImporter.h + B3D/B3DImporter.cpp + B3D/B3DImporter.h ) ADD_ASSIMP_IMPORTER( BVH - BVHLoader.cpp - BVHLoader.h + BVH/BVHLoader.cpp + BVH/BVHLoader.h ) ADD_ASSIMP_IMPORTER( COLLADA - ColladaHelper.h - ColladaLoader.cpp - ColladaLoader.h - ColladaParser.cpp - ColladaParser.h - ColladaExporter.h - ColladaExporter.cpp + Collada/ColladaHelper.h + Collada/ColladaLoader.cpp + Collada/ColladaLoader.h + Collada/ColladaParser.cpp + Collada/ColladaParser.h +) + +ADD_ASSIMP_EXPORTER( COLLADA + Collada/ColladaExporter.h + Collada/ColladaExporter.cpp ) ADD_ASSIMP_IMPORTER( DXF - DXFLoader.cpp - DXFLoader.h - DXFHelper.h + DXF/DXFLoader.cpp + DXF/DXFLoader.h + DXF/DXFHelper.h ) ADD_ASSIMP_IMPORTER( CSM - CSMLoader.cpp - CSMLoader.h + CSM/CSMLoader.cpp + CSM/CSMLoader.h ) ADD_ASSIMP_IMPORTER( HMP - HMPFileData.h - HMPLoader.cpp - HMPLoader.h - HalfLifeFileData.h + HMP/HMPFileData.h + HMP/HMPLoader.cpp + HMP/HMPLoader.h + HMP/HalfLifeFileData.h ) ADD_ASSIMP_IMPORTER( IRRMESH - IRRMeshLoader.cpp - IRRMeshLoader.h - IRRShared.cpp - IRRShared.h + Irr/IRRMeshLoader.cpp + Irr/IRRMeshLoader.h + Irr/IRRShared.cpp + Irr/IRRShared.h ) ADD_ASSIMP_IMPORTER( IRR - IRRLoader.cpp - IRRLoader.h - IRRShared.cpp - IRRShared.h + Irr/IRRLoader.cpp + Irr/IRRLoader.h + Irr/IRRShared.cpp + Irr/IRRShared.h ) ADD_ASSIMP_IMPORTER( LWO - LWOAnimation.cpp - LWOAnimation.h - LWOBLoader.cpp - LWOFileData.h - LWOLoader.cpp - LWOLoader.h - LWOMaterial.cpp + LWO/LWOAnimation.cpp + LWO/LWOAnimation.h + LWO/LWOBLoader.cpp + LWO/LWOFileData.h + LWO/LWOLoader.cpp + LWO/LWOLoader.h + LWO/LWOMaterial.cpp ) ADD_ASSIMP_IMPORTER( LWS - LWSLoader.cpp - LWSLoader.h + LWS/LWSLoader.cpp + LWS/LWSLoader.h ) ADD_ASSIMP_IMPORTER( MD2 - MD2FileData.h - MD2Loader.cpp - MD2Loader.h - MD2NormalTable.h + MD2/MD2FileData.h + MD2/MD2Loader.cpp + MD2/MD2Loader.h + MD2/MD2NormalTable.h ) ADD_ASSIMP_IMPORTER( MD3 - MD3FileData.h - MD3Loader.cpp - MD3Loader.h + MD3/MD3FileData.h + MD3/MD3Loader.cpp + MD3/MD3Loader.h ) ADD_ASSIMP_IMPORTER( MD5 - MD5Loader.cpp - MD5Loader.h - MD5Parser.cpp - MD5Parser.h + MD5/MD5Loader.cpp + MD5/MD5Loader.h + MD5/MD5Parser.cpp + MD5/MD5Parser.h ) ADD_ASSIMP_IMPORTER( MDC - MDCFileData.h - MDCLoader.cpp - MDCLoader.h - MDCNormalTable.h + MDC/MDCFileData.h + MDC/MDCLoader.cpp + MDC/MDCLoader.h + MDC/MDCNormalTable.h ) ADD_ASSIMP_IMPORTER( MDL - MDLDefaultColorMap.h - MDLFileData.h - MDLLoader.cpp - MDLLoader.h - MDLMaterialLoader.cpp + MDL/MDLDefaultColorMap.h + MDL/MDLFileData.h + MDL/MDLLoader.cpp + MDL/MDLLoader.h + MDL/MDLMaterialLoader.cpp ) SET( MaterialSystem_SRCS - MaterialSystem.cpp - MaterialSystem.h + Material/MaterialSystem.cpp + Material/MaterialSystem.h ) SOURCE_GROUP( MaterialSystem FILES ${MaterialSystem_SRCS}) ADD_ASSIMP_IMPORTER( NFF - NFFLoader.cpp - NFFLoader.h + NFF/NFFLoader.cpp + NFF/NFFLoader.h ) ADD_ASSIMP_IMPORTER( NDO - NDOLoader.cpp - NDOLoader.h + NDO/NDOLoader.cpp + NDO/NDOLoader.h ) ADD_ASSIMP_IMPORTER( OFF - OFFLoader.cpp - OFFLoader.h + OFF/OFFLoader.cpp + OFF/OFFLoader.h ) ADD_ASSIMP_IMPORTER( OBJ - ObjFileData.h - ObjFileImporter.cpp - ObjFileImporter.h - ObjFileMtlImporter.cpp - ObjFileMtlImporter.h - ObjFileParser.cpp - ObjFileParser.h - ObjTools.h - ObjExporter.h - ObjExporter.cpp + Obj/ObjFileData.h + Obj/ObjFileImporter.cpp + Obj/ObjFileImporter.h + Obj/ObjFileMtlImporter.cpp + Obj/ObjFileMtlImporter.h + Obj/ObjFileParser.cpp + Obj/ObjFileParser.h + Obj/ObjTools.h +) + +ADD_ASSIMP_EXPORTER( OBJ + Obj/ObjExporter.h + Obj/ObjExporter.cpp ) ADD_ASSIMP_IMPORTER( OGRE - OgreImporter.h - OgreStructs.h - OgreParsingUtils.h - OgreBinarySerializer.h - OgreXmlSerializer.h - OgreImporter.cpp - OgreStructs.cpp - OgreBinarySerializer.cpp - OgreXmlSerializer.cpp - OgreMaterial.cpp + Ogre/OgreImporter.h + Ogre/OgreStructs.h + Ogre/OgreParsingUtils.h + Ogre/OgreBinarySerializer.h + Ogre/OgreXmlSerializer.h + Ogre/OgreImporter.cpp + Ogre/OgreStructs.cpp + Ogre/OgreBinarySerializer.cpp + Ogre/OgreXmlSerializer.cpp + Ogre/OgreMaterial.cpp ) ADD_ASSIMP_IMPORTER( OPENGEX - OpenGEXExporter.cpp - OpenGEXExporter.h - OpenGEXImporter.cpp - OpenGEXImporter.h - OpenGEXStructs.h + OpenGEX/OpenGEXImporter.cpp + OpenGEX/OpenGEXImporter.h + OpenGEX/OpenGEXStructs.h +) + +ADD_ASSIMP_EXPORTER( OPENGEX + OpenGEX/OpenGEXExporter.cpp + OpenGEX/OpenGEXExporter.h ) ADD_ASSIMP_IMPORTER( PLY - PlyLoader.cpp - PlyLoader.h - PlyParser.cpp - PlyParser.h - PlyExporter.cpp - PlyExporter.h + Ply/PlyLoader.cpp + Ply/PlyLoader.h + Ply/PlyParser.cpp + Ply/PlyParser.h +) + +ADD_ASSIMP_EXPORTER( PLY + Ply/PlyExporter.cpp + Ply/PlyExporter.h ) ADD_ASSIMP_IMPORTER( MS3D - MS3DLoader.cpp - MS3DLoader.h + MS3D/MS3DLoader.cpp + MS3D/MS3DLoader.h ) ADD_ASSIMP_IMPORTER( COB - COBLoader.cpp - COBLoader.h - COBScene.h + COB/COBLoader.cpp + COB/COBLoader.h + COB/COBScene.h ) ADD_ASSIMP_IMPORTER( BLEND - BlenderLoader.cpp - BlenderLoader.h - BlenderDNA.cpp - BlenderDNA.h - BlenderDNA.inl - BlenderScene.cpp - BlenderScene.h - BlenderSceneGen.h - BlenderIntermediate.h - BlenderModifier.h - BlenderModifier.cpp - BlenderBMesh.h - BlenderBMesh.cpp - BlenderTessellator.h - BlenderTessellator.cpp - BlenderCustomData.h - BlenderCustomData.cpp + Blender/BlenderLoader.cpp + Blender/BlenderLoader.h + Blender/BlenderDNA.cpp + Blender/BlenderDNA.h + Blender/BlenderDNA.inl + Blender/BlenderScene.cpp + Blender/BlenderScene.h + Blender/BlenderSceneGen.h + Blender/BlenderIntermediate.h + Blender/BlenderModifier.h + Blender/BlenderModifier.cpp + Blender/BlenderBMesh.h + Blender/BlenderBMesh.cpp + Blender/BlenderTessellator.h + Blender/BlenderTessellator.cpp + Blender/BlenderCustomData.h + Blender/BlenderCustomData.cpp ) ADD_ASSIMP_IMPORTER( IFC @@ -506,103 +572,107 @@ if (ASSIMP_BUILD_IFC_IMPORTER) endif (ASSIMP_BUILD_IFC_IMPORTER) ADD_ASSIMP_IMPORTER( XGL - XGLLoader.cpp - XGLLoader.h + XGL/XGLLoader.cpp + XGL/XGLLoader.h ) ADD_ASSIMP_IMPORTER( FBX - FBXImporter.cpp - FBXCompileConfig.h - FBXImporter.h - FBXParser.cpp - FBXParser.h - FBXTokenizer.cpp - FBXTokenizer.h - FBXImportSettings.h - FBXConverter.h - FBXConverter.cpp - FBXUtil.h - FBXUtil.cpp - FBXDocument.h - FBXDocument.cpp - FBXProperties.h - FBXProperties.cpp - FBXMeshGeometry.h - FBXMeshGeometry.cpp - FBXMaterial.cpp - FBXModel.cpp - FBXAnimation.cpp - FBXNodeAttribute.cpp - FBXDeformer.cpp - FBXBinaryTokenizer.cpp - FBXDocumentUtil.cpp - FBXExporter.h - FBXExporter.cpp - FBXExportNode.h - FBXExportNode.cpp - FBXExportProperty.h - FBXExportProperty.cpp - FBXCommon.h + FBX/FBXImporter.cpp + FBX/FBXCompileConfig.h + FBX/FBXImporter.h + FBX/FBXParser.cpp + FBX/FBXParser.h + FBX/FBXTokenizer.cpp + FBX/FBXTokenizer.h + FBX/FBXImportSettings.h + FBX/FBXConverter.h + FBX/FBXConverter.cpp + FBX/FBXUtil.h + FBX/FBXUtil.cpp + FBX/FBXDocument.h + FBX/FBXDocument.cpp + FBX/FBXProperties.h + FBX/FBXProperties.cpp + FBX/FBXMeshGeometry.h + FBX/FBXMeshGeometry.cpp + FBX/FBXMaterial.cpp + FBX/FBXModel.cpp + FBX/FBXAnimation.cpp + FBX/FBXNodeAttribute.cpp + FBX/FBXDeformer.cpp + FBX/FBXBinaryTokenizer.cpp + FBX/FBXDocumentUtil.cpp + FBX/FBXCommon.h +) + +ADD_ASSIMP_EXPORTER( FBX + FBX/FBXExporter.h + FBX/FBXExporter.cpp + FBX/FBXExportNode.h + FBX/FBXExportNode.cpp + FBX/FBXExportProperty.h + FBX/FBXExportProperty.cpp ) SET( PostProcessing_SRCS - CalcTangentsProcess.cpp - CalcTangentsProcess.h - ComputeUVMappingProcess.cpp - ComputeUVMappingProcess.h - ConvertToLHProcess.cpp - ConvertToLHProcess.h - EmbedTexturesProcess.cpp - EmbedTexturesProcess.h - FindDegenerates.cpp - FindDegenerates.h - FindInstancesProcess.cpp - FindInstancesProcess.h - FindInvalidDataProcess.cpp - FindInvalidDataProcess.h - FixNormalsStep.cpp - FixNormalsStep.h - DropFaceNormalsProcess.cpp - DropFaceNormalsProcess.h - GenFaceNormalsProcess.cpp - GenFaceNormalsProcess.h - GenVertexNormalsProcess.cpp - GenVertexNormalsProcess.h - PretransformVertices.cpp - PretransformVertices.h - ImproveCacheLocality.cpp - ImproveCacheLocality.h - JoinVerticesProcess.cpp - JoinVerticesProcess.h - LimitBoneWeightsProcess.cpp - LimitBoneWeightsProcess.h - RemoveRedundantMaterials.cpp - RemoveRedundantMaterials.h - RemoveVCProcess.cpp - RemoveVCProcess.h - SortByPTypeProcess.cpp - SortByPTypeProcess.h - SplitLargeMeshes.cpp - SplitLargeMeshes.h - TextureTransform.cpp - TextureTransform.h - TriangulateProcess.cpp - TriangulateProcess.h - ValidateDataStructure.cpp - ValidateDataStructure.h - OptimizeGraph.cpp - OptimizeGraph.h - OptimizeMeshes.cpp - OptimizeMeshes.h - DeboneProcess.cpp - DeboneProcess.h - ProcessHelper.h - ProcessHelper.cpp - PolyTools.h - MakeVerboseFormat.cpp - MakeVerboseFormat.h - ScaleProcess.cpp - ScaleProcess.h + PostProcessing/CalcTangentsProcess.cpp + PostProcessing/CalcTangentsProcess.h + PostProcessing/ComputeUVMappingProcess.cpp + PostProcessing/ComputeUVMappingProcess.h + PostProcessing/ConvertToLHProcess.cpp + PostProcessing/ConvertToLHProcess.h + PostProcessing/EmbedTexturesProcess.cpp + PostProcessing/EmbedTexturesProcess.h + PostProcessing/FindDegenerates.cpp + PostProcessing/FindDegenerates.h + PostProcessing/FindInstancesProcess.cpp + PostProcessing/FindInstancesProcess.h + PostProcessing/FindInvalidDataProcess.cpp + PostProcessing/FindInvalidDataProcess.h + PostProcessing/FixNormalsStep.cpp + PostProcessing/FixNormalsStep.h + PostProcessing/DropFaceNormalsProcess.cpp + PostProcessing/DropFaceNormalsProcess.h + PostProcessing/GenFaceNormalsProcess.cpp + PostProcessing/GenFaceNormalsProcess.h + PostProcessing/GenVertexNormalsProcess.cpp + PostProcessing/GenVertexNormalsProcess.h + PostProcessing/PretransformVertices.cpp + PostProcessing/PretransformVertices.h + PostProcessing/ImproveCacheLocality.cpp + PostProcessing/ImproveCacheLocality.h + PostProcessing/JoinVerticesProcess.cpp + PostProcessing/JoinVerticesProcess.h + PostProcessing/LimitBoneWeightsProcess.cpp + PostProcessing/LimitBoneWeightsProcess.h + PostProcessing/RemoveRedundantMaterials.cpp + PostProcessing/RemoveRedundantMaterials.h + PostProcessing/RemoveVCProcess.cpp + PostProcessing/RemoveVCProcess.h + PostProcessing/SortByPTypeProcess.cpp + PostProcessing/SortByPTypeProcess.h + PostProcessing/SplitLargeMeshes.cpp + PostProcessing/SplitLargeMeshes.h + PostProcessing/TextureTransform.cpp + PostProcessing/TextureTransform.h + PostProcessing/TriangulateProcess.cpp + PostProcessing/TriangulateProcess.h + PostProcessing/ValidateDataStructure.cpp + PostProcessing/ValidateDataStructure.h + PostProcessing/OptimizeGraph.cpp + PostProcessing/OptimizeGraph.h + PostProcessing/OptimizeMeshes.cpp + PostProcessing/OptimizeMeshes.h + PostProcessing/DeboneProcess.cpp + PostProcessing/DeboneProcess.h + PostProcessing/ProcessHelper.h + PostProcessing/ProcessHelper.cpp + PostProcessing/MakeVerboseFormat.cpp + PostProcessing/MakeVerboseFormat.h + PostProcessing/ScaleProcess.cpp + PostProcessing/ScaleProcess.h + PostProcessing/GenBoundingBoxesProcess.cpp + PostProcessing/GenBoundingBoxesProcess.h ) SOURCE_GROUP( PostProcessing FILES ${PostProcessing_SRCS}) @@ -610,252 +680,354 @@ SET( IrrXML_SRCS ${HEADER_PATH}/irrXMLWrapper.h ) SOURCE_GROUP( IrrXML FILES ${IrrXML_SRCS}) ADD_ASSIMP_IMPORTER( Q3D - Q3DLoader.cpp - Q3DLoader.h + Q3D/Q3DLoader.cpp + Q3D/Q3DLoader.h ) ADD_ASSIMP_IMPORTER( Q3BSP - Q3BSPFileData.h - Q3BSPFileParser.h - Q3BSPFileParser.cpp - Q3BSPFileImporter.h - Q3BSPFileImporter.cpp - Q3BSPZipArchive.h - Q3BSPZipArchive.cpp + Q3BSP/Q3BSPFileData.h + Q3BSP/Q3BSPFileParser.h + Q3BSP/Q3BSPFileParser.cpp + Q3BSP/Q3BSPFileImporter.h + Q3BSP/Q3BSPFileImporter.cpp ) ADD_ASSIMP_IMPORTER( RAW - RawLoader.cpp - RawLoader.h + Raw/RawLoader.cpp + Raw/RawLoader.h ) ADD_ASSIMP_IMPORTER( SIB - SIBImporter.cpp - SIBImporter.h + SIB/SIBImporter.cpp + SIB/SIBImporter.h ) ADD_ASSIMP_IMPORTER( SMD - SMDLoader.cpp - SMDLoader.h + SMD/SMDLoader.cpp + SMD/SMDLoader.h ) ADD_ASSIMP_IMPORTER( STL - STLLoader.cpp - STLLoader.h - STLExporter.h - STLExporter.cpp + STL/STLLoader.cpp + STL/STLLoader.h +) + +ADD_ASSIMP_EXPORTER( STL + STL/STLExporter.h + STL/STLExporter.cpp ) ADD_ASSIMP_IMPORTER( TERRAGEN - TerragenLoader.cpp - TerragenLoader.h + Terragen/TerragenLoader.cpp + Terragen/TerragenLoader.h ) ADD_ASSIMP_IMPORTER( 3D - UnrealLoader.cpp - UnrealLoader.h + Unreal/UnrealLoader.cpp + Unreal/UnrealLoader.h ) ADD_ASSIMP_IMPORTER( X - XFileHelper.h - XFileImporter.cpp - XFileImporter.h - XFileParser.cpp - XFileParser.h - XFileExporter.h - XFileExporter.cpp + X/XFileHelper.h + X/XFileImporter.cpp + X/XFileImporter.h + X/XFileParser.cpp + X/XFileParser.h +) + +ADD_ASSIMP_EXPORTER( X + X/XFileExporter.h + X/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 - FIReader.hpp - FIReader.cpp - X3DVocabulary.cpp + X3D/X3DImporter.cpp + X3D/X3DImporter.hpp + X3D/X3DImporter_Geometry2D.cpp + X3D/X3DImporter_Geometry3D.cpp + X3D/X3DImporter_Group.cpp + X3D/X3DImporter_Light.cpp + X3D/X3DImporter_Macro.hpp + X3D/X3DImporter_Metadata.cpp + X3D/X3DImporter_Networking.cpp + X3D/X3DImporter_Node.hpp + X3D/X3DImporter_Postprocess.cpp + X3D/X3DImporter_Rendering.cpp + X3D/X3DImporter_Shape.cpp + X3D/X3DImporter_Texturing.cpp + X3D/FIReader.hpp + X3D/FIReader.cpp + X3D/X3DVocabulary.cpp +) + +ADD_ASSIMP_EXPORTER( X3D + X3D/X3DExporter.cpp + X3D/X3DExporter.hpp ) ADD_ASSIMP_IMPORTER( GLTF - glTFAsset.h - glTFAsset.inl - glTFAssetWriter.h - glTFAssetWriter.inl - glTFImporter.cpp - glTFImporter.h - glTFExporter.h - glTFExporter.cpp - glTF2Asset.h - glTF2Asset.inl - glTF2AssetWriter.h - glTF2AssetWriter.inl - glTF2Importer.cpp - glTF2Importer.h - glTF2Exporter.h - glTF2Exporter.cpp + glTF/glTFCommon.h + glTF/glTFCommon.cpp + glTF/glTFAsset.h + glTF/glTFAsset.inl + glTF/glTFAssetWriter.h + glTF/glTFAssetWriter.inl + glTF/glTFImporter.cpp + glTF/glTFImporter.h + glTF2/glTF2Asset.h + glTF2/glTF2Asset.inl + glTF2/glTF2AssetWriter.h + glTF2/glTF2AssetWriter.inl + glTF2/glTF2Importer.cpp + glTF2/glTF2Importer.h +) + +ADD_ASSIMP_EXPORTER( GLTF + glTF/glTFExporter.h + glTF/glTFExporter.cpp + glTF2/glTF2Exporter.h + glTF2/glTF2Exporter.cpp ) ADD_ASSIMP_IMPORTER( 3MF - D3MFImporter.h - D3MFImporter.cpp - D3MFExporter.h - D3MFExporter.cpp - D3MFOpcPackage.h - D3MFOpcPackage.cpp - 3MFXmlTags.h + 3MF/D3MFImporter.h + 3MF/D3MFImporter.cpp + 3MF/D3MFOpcPackage.h + 3MF/D3MFOpcPackage.cpp + 3MF/3MFXmlTags.h +) + +ADD_ASSIMP_EXPORTER( 3MF + 3MF/D3MFExporter.h + 3MF/D3MFExporter.cpp ) ADD_ASSIMP_IMPORTER( MMD - MMDCpp14.h - MMDImporter.cpp - MMDImporter.h - MMDPmdParser.h - MMDPmxParser.h - MMDPmxParser.cpp - MMDVmdParser.h + MMD/MMDCpp14.h + MMD/MMDImporter.cpp + MMD/MMDImporter.h + MMD/MMDPmdParser.h + MMD/MMDPmxParser.h + MMD/MMDPmxParser.cpp + MMD/MMDVmdParser.h ) -SET( Step_SRCS - STEPFile.h +ADD_ASSIMP_EXPORTER( ASSJSON + Assjson/cencode.c + Assjson/cencode.h + Assjson/json_exporter.cpp + Assjson/mesh_splitter.cpp + Assjson/mesh_splitter.h +) + +# Workaround for issue #2406 - force problematic large file to be optimized to prevent string table overflow error +# Used -Os instead of -O2 as previous issues had mentioned, since -Os is roughly speaking -O2, excluding any +# optimizations that take up extra space. Given that the issue is a string table overflowing, -Os seemed appropriate +# Also, I'm not positive if both link & compile flags are needed, but this hopefully ensures that the issue should not +# recur for edge cases such as static builds. +if ((CMAKE_COMPILER_IS_MINGW) AND (CMAKE_BUILD_TYPE MATCHES Debug)) + message("-- Applying MinGW StepFileGen1.cpp Debug Workaround") + SET_SOURCE_FILES_PROPERTIES(Importer/StepFile/StepFileGen1.cpp PROPERTIES COMPILE_FLAGS -Os ) + SET_SOURCE_FILES_PROPERTIES(Importer/StepFile/StepFileGen1.cpp PROPERTIES LINK_FLAGS -Os ) + SET_SOURCE_FILES_PROPERTIES(Importer/StepFile/StepFileGen1.cpp PROPERTIES STATIC_LIBRARY_FLAGS -Os ) +endif() + +ADD_ASSIMP_IMPORTER( STEP + Step/STEPFile.h Importer/StepFile/StepFileImporter.h Importer/StepFile/StepFileImporter.cpp Importer/StepFile/StepFileGen1.cpp Importer/StepFile/StepFileGen2.cpp Importer/StepFile/StepFileGen3.cpp Importer/StepFile/StepReaderGen.h - StepExporter.h - StepExporter.cpp ) -SOURCE_GROUP( Step FILES ${Step_SRCS}) -SET( Exporter_SRCS - Exporter.cpp - AssimpCExport.cpp - ${HEADER_PATH}/BlobIOSystem.h +ADD_ASSIMP_EXPORTER( STEP + Step/StepExporter.h + Step/StepExporter.cpp ) -SOURCE_GROUP( Exporter FILES ${Exporter_SRCS}) + +if ((NOT ASSIMP_NO_EXPORT) OR (NOT ASSIMP_EXPORTERS_ENABLED STREQUAL "")) + SET( Exporter_SRCS + Common/Exporter.cpp + CApi/AssimpCExport.cpp + ${HEADER_PATH}/BlobIOSystem.h + ) + SOURCE_GROUP( Exporter FILES ${Exporter_SRCS}) +endif() SET( Extra_SRCS MD4FileData.h ) SOURCE_GROUP( Extra FILES ${Extra_SRCS}) +# irrXML +IF(HUNTER_ENABLED) + hunter_add_package(irrXML) + find_package(irrXML CONFIG REQUIRED) +ELSE(HUNTER_ENABLED) + # irrXML already included in contrib directory by parent CMakeLists.txt. +ENDIF(HUNTER_ENABLED) -SET( Clipper_SRCS - ../contrib/clipper/clipper.hpp - ../contrib/clipper/clipper.cpp -) -SOURCE_GROUP( Clipper FILES ${Clipper_SRCS}) +# utf8 +IF(HUNTER_ENABLED) + hunter_add_package(utf8) + find_package(utf8 CONFIG REQUIRED) +ELSE(HUNTER_ENABLED) + # utf8 is header-only, so Assimp doesn't need to do anything. +ENDIF(HUNTER_ENABLED) -SET( Poly2Tri_SRCS - ../contrib/poly2tri/poly2tri/common/shapes.cc - ../contrib/poly2tri/poly2tri/common/shapes.h - ../contrib/poly2tri/poly2tri/common/utils.h - ../contrib/poly2tri/poly2tri/sweep/advancing_front.h - ../contrib/poly2tri/poly2tri/sweep/advancing_front.cc - ../contrib/poly2tri/poly2tri/sweep/cdt.cc - ../contrib/poly2tri/poly2tri/sweep/cdt.h - ../contrib/poly2tri/poly2tri/sweep/sweep.cc - ../contrib/poly2tri/poly2tri/sweep/sweep.h - ../contrib/poly2tri/poly2tri/sweep/sweep_context.cc - ../contrib/poly2tri/poly2tri/sweep/sweep_context.h -) -SOURCE_GROUP( Poly2Tri FILES ${Poly2Tri_SRCS}) +# polyclipping +IF(HUNTER_ENABLED) + hunter_add_package(polyclipping) + find_package(polyclipping CONFIG REQUIRED) +ELSE(HUNTER_ENABLED) + SET( Clipper_SRCS + ../contrib/clipper/clipper.hpp + ../contrib/clipper/clipper.cpp + ) + SOURCE_GROUP( Contrib\\Clipper FILES ${Clipper_SRCS}) +ENDIF(HUNTER_ENABLED) -SET( unzip_SRCS - ../contrib/unzip/crypt.h - ../contrib/unzip/ioapi.c - ../contrib/unzip/ioapi.h - ../contrib/unzip/unzip.c - ../contrib/unzip/unzip.h -) -SOURCE_GROUP( unzip FILES ${unzip_SRCS}) +# poly2tri +IF(HUNTER_ENABLED) + hunter_add_package(poly2tri) + find_package(poly2tri CONFIG REQUIRED) +ELSE(HUNTER_ENABLED) + SET( Poly2Tri_SRCS + ../contrib/poly2tri/poly2tri/common/shapes.cc + ../contrib/poly2tri/poly2tri/common/shapes.h + ../contrib/poly2tri/poly2tri/common/utils.h + ../contrib/poly2tri/poly2tri/sweep/advancing_front.h + ../contrib/poly2tri/poly2tri/sweep/advancing_front.cc + ../contrib/poly2tri/poly2tri/sweep/cdt.cc + ../contrib/poly2tri/poly2tri/sweep/cdt.h + ../contrib/poly2tri/poly2tri/sweep/sweep.cc + ../contrib/poly2tri/poly2tri/sweep/sweep.h + ../contrib/poly2tri/poly2tri/sweep/sweep_context.cc + ../contrib/poly2tri/poly2tri/sweep/sweep_context.h + ) + SOURCE_GROUP( Contrib\\Poly2Tri FILES ${Poly2Tri_SRCS}) +ENDIF(HUNTER_ENABLED) -SET( ziplib_SRCS - ../contrib/zip/src/miniz.h - ../contrib/zip/src/zip.c - ../contrib/zip/src/zip.h -) +# minizip/unzip +IF(HUNTER_ENABLED) + hunter_add_package(minizip) + find_package(minizip CONFIG REQUIRED) +ELSE(HUNTER_ENABLED) + SET( unzip_SRCS + ../contrib/unzip/crypt.h + ../contrib/unzip/ioapi.c + ../contrib/unzip/ioapi.h + ../contrib/unzip/unzip.c + ../contrib/unzip/unzip.h + ) + SOURCE_GROUP(Contrib\\unzip FILES ${unzip_SRCS}) +ENDIF(HUNTER_ENABLED) -SOURCE_GROUP( ziplib FILES ${ziplib_SRCS} ) +# zip (https://github.com/kuba--/zip) +IF(HUNTER_ENABLED) + hunter_add_package(zip) + find_package(zip CONFIG REQUIRED) +ELSE(HUNTER_ENABLED) + SET( ziplib_SRCS + ../contrib/zip/src/miniz.h + ../contrib/zip/src/zip.c + ../contrib/zip/src/zip.h + ) -SET ( openddl_parser_SRCS - ../contrib/openddlparser/code/OpenDDLParser.cpp - ../contrib/openddlparser/code/DDLNode.cpp - ../contrib/openddlparser/code/OpenDDLCommon.cpp - ../contrib/openddlparser/code/OpenDDLExport.cpp - ../contrib/openddlparser/code/Value.cpp - ../contrib/openddlparser/code/OpenDDLStream.cpp - ../contrib/openddlparser/include/openddlparser/OpenDDLParser.h - ../contrib/openddlparser/include/openddlparser/OpenDDLParserUtils.h - ../contrib/openddlparser/include/openddlparser/OpenDDLCommon.h - ../contrib/openddlparser/include/openddlparser/OpenDDLExport.h - ../contrib/openddlparser/include/openddlparser/OpenDDLStream.h - ../contrib/openddlparser/include/openddlparser/DDLNode.h - ../contrib/openddlparser/include/openddlparser/Value.h -) -SOURCE_GROUP( openddl_parser FILES ${openddl_parser_SRCS}) + # TODO if cmake required version has been updated to >3.12.0, collapse this to the second case only + if(${CMAKE_VERSION} VERSION_LESS "3.12.0") + add_definitions(-DMINIZ_USE_UNALIGNED_LOADS_AND_STORES=0) + else() + add_compile_definitions(MINIZ_USE_UNALIGNED_LOADS_AND_STORES=0) + endif() -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}) + SOURCE_GROUP( ziplib FILES ${ziplib_SRCS} ) +ENDIF(HUNTER_ENABLED) + +# openddlparser +IF(HUNTER_ENABLED) + hunter_add_package(openddlparser) + find_package(openddlparser CONFIG REQUIRED) +ELSE(HUNTER_ENABLED) + SET ( openddl_parser_SRCS + ../contrib/openddlparser/code/OpenDDLParser.cpp + ../contrib/openddlparser/code/DDLNode.cpp + ../contrib/openddlparser/code/OpenDDLCommon.cpp + ../contrib/openddlparser/code/OpenDDLExport.cpp + ../contrib/openddlparser/code/Value.cpp + ../contrib/openddlparser/code/OpenDDLStream.cpp + ../contrib/openddlparser/include/openddlparser/OpenDDLParser.h + ../contrib/openddlparser/include/openddlparser/OpenDDLParserUtils.h + ../contrib/openddlparser/include/openddlparser/OpenDDLCommon.h + ../contrib/openddlparser/include/openddlparser/OpenDDLExport.h + ../contrib/openddlparser/include/openddlparser/OpenDDLStream.h + ../contrib/openddlparser/include/openddlparser/DDLNode.h + ../contrib/openddlparser/include/openddlparser/Value.h + ) + SOURCE_GROUP( Contrib\\openddl_parser FILES ${openddl_parser_SRCS}) +ENDIF(HUNTER_ENABLED) + +# Open3DGC +IF(HUNTER_ENABLED) + # Nothing to do, not available in Hunter yet. +ELSE(HUNTER_ENABLED) + 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( Contrib\\open3dgc FILES ${open3dgc_SRCS}) +ENDIF(HUNTER_ENABLED) # 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) +IF (NOT HUNTER_ENABLED AND (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.") + MESSAGE (INFO " Hunter enabled or 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 +IF(HUNTER_ENABLED) + hunter_add_package(RapidJSON) + find_package(RapidJSON CONFIG REQUIRED) +ELSE(HUNTER_ENABLED) + INCLUDE_DIRECTORIES( "../contrib/rapidjson/include" ) + INCLUDE_DIRECTORIES( "../contrib" ) +ENDIF(HUNTER_ENABLED) # VC2010 fixes if(MSVC10) @@ -872,29 +1044,36 @@ if ( MSVC ) ADD_DEFINITIONS( -D_CRT_SECURE_NO_WARNINGS ) endif ( MSVC ) -if (UNZIP_FOUND) - SET (unzip_compile_SRCS "") -else (UNZIP_FOUND) - SET (unzip_compile_SRCS ${unzip_SRCS}) - INCLUDE_DIRECTORIES( "../contrib/unzip/" ) -endif (UNZIP_FOUND) +IF(NOT HUNTER_ENABLED) + if (UNZIP_FOUND) + SET (unzip_compile_SRCS "") + else (UNZIP_FOUND) + SET (unzip_compile_SRCS ${unzip_SRCS}) + INCLUDE_DIRECTORIES( "../contrib/unzip/" ) + endif (UNZIP_FOUND) +ENDIF(NOT HUNTER_ENABLED) -MESSAGE(STATUS "Enabled formats:${ASSIMP_IMPORTERS_ENABLED}") -MESSAGE(STATUS "Disabled formats:${ASSIMP_IMPORTERS_DISABLED}") +MESSAGE(STATUS "Enabled importer formats:${ASSIMP_IMPORTERS_ENABLED}") +MESSAGE(STATUS "Disabled importer formats:${ASSIMP_IMPORTERS_DISABLED}") + +MESSAGE(STATUS "Enabled exporter formats:${ASSIMP_EXPORTERS_ENABLED}") +MESSAGE(STATUS "Disabled exporter formats:${ASSIMP_EXPORTERS_DISABLED}") SET( assimp_src # Assimp Files ${Core_SRCS} + ${CApi_SRCS} ${Common_SRCS} ${Logging_SRCS} ${Exporter_SRCS} ${PostProcessing_SRCS} ${MaterialSystem_SRCS} ${STEPParser_SRCS} - ${Step_SRCS} +# ${Step_SRCS} check if we need a different approach # Model Support ${ASSIMP_LOADER_SRCS} + ${ASSIMP_EXPORTER_SRCS} # Third-party libraries ${IrrXML_SRCS} @@ -908,14 +1087,15 @@ SET( assimp_src ${PUBLIC_HEADERS} ${COMPILER_HEADERS} - ) ADD_DEFINITIONS( -DOPENDDLPARSER_BUILD ) -INCLUDE_DIRECTORIES( - ${IRRXML_INCLUDE_DIR} - ../contrib/openddlparser/include -) +IF(NOT HUNTER_ENABLED) + INCLUDE_DIRECTORIES( + ${IRRXML_INCLUDE_DIR} + ../contrib/openddlparser/include + ) +ENDIF(NOT HUNTER_ENABLED) IF (ASSIMP_BUILD_NONFREE_C4D_IMPORTER) SET( assimp_src ${assimp_src} ${C4D_SRCS}) @@ -928,16 +1108,31 @@ ADD_LIBRARY(assimp::assimp ALIAS assimp) TARGET_INCLUDE_DIRECTORIES ( assimp PUBLIC $ $ - $ + $ ) -TARGET_LINK_LIBRARIES(assimp ${ZLIB_LIBRARIES} ${OPENDDL_PARSER_LIBRARIES} ${IRRXML_LIBRARY} ) +IF(HUNTER_ENABLED) + TARGET_LINK_LIBRARIES(assimp + PUBLIC + polyclipping::polyclipping + irrXML::irrXML + openddlparser::openddl_parser + poly2tri::poly2tri + minizip::minizip + ZLIB::zlib + RapidJSON::rapidjson + utf8::utf8 + zip::zip + ) +ELSE(HUNTER_ENABLED) + TARGET_LINK_LIBRARIES(assimp ${ZLIB_LIBRARIES} ${OPENDDL_PARSER_LIBRARIES} ${IRRXML_LIBRARY} ) +ENDIF(HUNTER_ENABLED) -if(ANDROID AND ASSIMP_ANDROID_JNIIOSYSTEM) +if(ASSIMP_ANDROID_JNIIOSYSTEM) set(ASSIMP_ANDROID_JNIIOSYSTEM_PATH port/AndroidJNI) add_subdirectory(../${ASSIMP_ANDROID_JNIIOSYSTEM_PATH}/ ../${ASSIMP_ANDROID_JNIIOSYSTEM_PATH}/) target_link_libraries(assimp android_jniiosystem) -endif(ANDROID AND ASSIMP_ANDROID_JNIIOSYSTEM) +endif(ASSIMP_ANDROID_JNIIOSYSTEM) IF (ASSIMP_BUILD_NONFREE_C4D_IMPORTER) TARGET_LINK_LIBRARIES(assimp optimized ${C4D_RELEASE_LIBRARIES}) @@ -947,26 +1142,41 @@ ENDIF (ASSIMP_BUILD_NONFREE_C4D_IMPORTER) if( MSVC ) # in order to prevent DLL hell, each of the DLLs have to be suffixed with the major version and msvc prefix - if( MSVC70 OR MSVC71 ) - set(MSVC_PREFIX "vc70") - elseif( MSVC80 ) - set(MSVC_PREFIX "vc80") - elseif( MSVC90 ) - set(MSVC_PREFIX "vc90") - elseif( MSVC10 ) - set(MSVC_PREFIX "vc100") - elseif( MSVC11 ) - set(MSVC_PREFIX "vc110") - elseif( MSVC12 ) - set(MSVC_PREFIX "vc120") - elseif( MSVC14 ) - set(MSVC_PREFIX "vc140") + # CMake 3.12 added a variable for this + if(MSVC_TOOLSET_VERSION) + set(MSVC_PREFIX "vc${MSVC_TOOLSET_VERSION}") else() - set(MSVC_PREFIX "vc150") + if( MSVC70 OR MSVC71 ) + set(MSVC_PREFIX "vc70") + elseif( MSVC80 ) + set(MSVC_PREFIX "vc80") + elseif( MSVC90 ) + set(MSVC_PREFIX "vc90") + elseif( MSVC10 ) + set(MSVC_PREFIX "vc100") + elseif( MSVC11 ) + set(MSVC_PREFIX "vc110") + elseif( MSVC12 ) + set(MSVC_PREFIX "vc120") + elseif( MSVC_VERSION LESS 1910) + set(MSVC_PREFIX "vc140") + elseif( MSVC_VERSION LESS 1920) + set(MSVC_PREFIX "vc141") + elseif( MSVC_VERSION LESS 1930) + set(MSVC_PREFIX "vc142") + else() + MESSAGE(WARNING "unknown msvc version ${MSVC_VERSION}") + set(MSVC_PREFIX "vc150") + endif() endif() set(LIBRARY_SUFFIX "${ASSIMP_LIBRARY_SUFFIX}-${MSVC_PREFIX}-mt" CACHE STRING "the suffix for the assimp windows library") endif() +if (${CMAKE_SYSTEM_NAME} MATCHES "WindowsStore") + target_compile_definitions(assimp PUBLIC WindowsStore) + TARGET_LINK_LIBRARIES(assimp advapi32) + #set(WindowsStore TRUE) +endif() SET_TARGET_PROPERTIES( assimp PROPERTIES VERSION ${ASSIMP_VERSION} SOVERSION ${ASSIMP_SOVERSION} # use full version @@ -998,24 +1208,37 @@ ENDIF(APPLE) # Build against external unzip, or add ../contrib/unzip so # assimp can #include "unzip.h" -if (UNZIP_FOUND) - INCLUDE_DIRECTORIES(${UNZIP_INCLUDE_DIRS}) - TARGET_LINK_LIBRARIES(assimp ${UNZIP_LIBRARIES}) -else (UNZIP_FOUND) - INCLUDE_DIRECTORIES("../") -endif (UNZIP_FOUND) +IF(NOT HUNTER_ENABLED) + if (UNZIP_FOUND) + INCLUDE_DIRECTORIES(${UNZIP_INCLUDE_DIRS}) + TARGET_LINK_LIBRARIES(assimp ${UNZIP_LIBRARIES}) + else (UNZIP_FOUND) + INCLUDE_DIRECTORIES("../") + endif (UNZIP_FOUND) +ENDIF(NOT HUNTER_ENABLED) # 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) +IF(HUNTER_ENABLED) + INSTALL( TARGETS assimp + EXPORT "${TARGETS_EXPORT_NAME}" + LIBRARY DESTINATION ${ASSIMP_LIB_INSTALL_DIR} + ARCHIVE DESTINATION ${ASSIMP_LIB_INSTALL_DIR} + RUNTIME DESTINATION ${ASSIMP_BIN_INSTALL_DIR} + FRAMEWORK DESTINATION ${ASSIMP_LIB_INSTALL_DIR} + COMPONENT ${LIBASSIMP_COMPONENT} + INCLUDES DESTINATION "include") +ELSE(HUNTER_ENABLED) INSTALL( TARGETS assimp - LIBRARY DESTINATION ${ASSIMP_LIB_INSTALL_DIR} - ARCHIVE DESTINATION ${ASSIMP_LIB_INSTALL_DIR} - RUNTIME DESTINATION ${ASSIMP_BIN_INSTALL_DIR} - FRAMEWORK DESTINATION ${ASSIMP_LIB_INSTALL_DIR} - COMPONENT ${LIBASSIMP_COMPONENT}) + LIBRARY DESTINATION ${ASSIMP_LIB_INSTALL_DIR} + ARCHIVE DESTINATION ${ASSIMP_LIB_INSTALL_DIR} + RUNTIME DESTINATION ${ASSIMP_BIN_INSTALL_DIR} + FRAMEWORK DESTINATION ${ASSIMP_LIB_INSTALL_DIR} + COMPONENT ${LIBASSIMP_COMPONENT}) +ENDIF(HUNTER_ENABLED) INSTALL( FILES ${PUBLIC_HEADERS} DESTINATION ${ASSIMP_INCLUDE_INSTALL_DIR}/assimp COMPONENT assimp-dev) INSTALL( FILES ${COMPILER_HEADERS} DESTINATION ${ASSIMP_INCLUDE_INSTALL_DIR}/assimp/Compiler COMPONENT assimp-dev) @@ -1026,6 +1249,16 @@ if (ASSIMP_ANDROID_JNIIOSYSTEM) ENDIF(ASSIMP_ANDROID_JNIIOSYSTEM) if(MSVC AND ASSIMP_INSTALL_PDB) + # When only the static library is built, these properties must + # be set to ensure the static lib .pdb is staged for installation. + IF(NOT BUILD_SHARED_LIBS) + SET_TARGET_PROPERTIES( assimp PROPERTIES + COMPILE_PDB_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + COMPILE_PDB_NAME assimp${LIBRARY_SUFFIX} + COMPILE_PDB_NAME_DEBUG assimp${LIBRARY_SUFFIX}${CMAKE_DEBUG_POSTFIX} + ) + ENDIF() + IF(CMAKE_GENERATOR MATCHES "^Visual Studio") install(FILES ${Assimp_BINARY_DIR}/code/Debug/assimp${LIBRARY_SUFFIX}${CMAKE_DEBUG_POSTFIX}.pdb DESTINATION ${ASSIMP_LIB_INSTALL_DIR} diff --git a/third_party/libassimp/code/COBLoader.cpp b/third_party/libassimp/code/COB/COBLoader.cpp similarity index 98% rename from third_party/libassimp/code/COBLoader.cpp rename to third_party/libassimp/code/COB/COBLoader.cpp index a8e41dbbca..19e3cd59ea 100644 --- a/third_party/libassimp/code/COBLoader.cpp +++ b/third_party/libassimp/code/COB/COBLoader.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -45,20 +45,22 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_COB_IMPORTER -#include "COBLoader.h" -#include "COBScene.h" -#include "ConvertToLHProcess.h" +#include "COB/COBLoader.h" +#include "COB/COBScene.h" +#include "PostProcessing/ConvertToLHProcess.h" + #include #include #include #include #include -#include #include #include #include #include +#include + using namespace Assimp; using namespace Assimp::COB; using namespace Assimp::Formatter; @@ -144,7 +146,7 @@ void COBImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOS // check header char head[32]; stream->CopyAndAdvance(head,32); - if (strncmp(head,"Caligari ",9)) { + if (strncmp(head,"Caligari ",9) != 0) { ThrowException("Could not found magic id: `Caligari`"); } @@ -656,14 +658,14 @@ void COBImporter::ReadLght_Ascii(Scene& out, LineSplitter& splitter, const Chunk ReadFloat3Tuple_Ascii(msh.color ,&rgb); SkipSpaces(&rgb); - if (strncmp(rgb,"cone angle",10)) { + if (strncmp(rgb,"cone angle",10) != 0) { ASSIMP_LOG_WARN_F( "Expected `cone angle` entity in `color` line in `Lght` chunk ", nfo.id ); } SkipSpaces(rgb+10,&rgb); msh.angle = fast_atof(&rgb); SkipSpaces(&rgb); - if (strncmp(rgb,"inner angle",11)) { + if (strncmp(rgb,"inner angle",11) != 0) { ASSIMP_LOG_WARN_F( "Expected `inner angle` entity in `color` line in `Lght` chunk ", nfo.id); } SkipSpaces(rgb+11,&rgb); @@ -896,6 +898,7 @@ public: : nfo(nfo) , reader(reader) , cur(reader.GetCurrentPos()) { + // empty } ~chunk_guard() { @@ -903,7 +906,7 @@ public: if(nfo.size != static_cast(-1)) { try { reader.IncPtr( static_cast< int >( nfo.size ) - reader.GetCurrentPos() + cur ); - } catch ( DeadlyImportError e ) { + } catch (const DeadlyImportError& ) { // out of limit so correct the value reader.IncPtr( reader.GetReadLimit() ); } @@ -911,15 +914,17 @@ public: } private: - const COB::ChunkInfo& nfo; StreamReaderLE& reader; long cur; }; // ------------------------------------------------------------------------------------------------ -void COBImporter::ReadBinaryFile(Scene& out, StreamReaderLE* reader) -{ +void COBImporter::ReadBinaryFile(Scene& out, StreamReaderLE* reader) { + if (nullptr == reader) { + return; + } + while(1) { std::string type; type += reader -> GetI1() @@ -1214,7 +1219,7 @@ void COBImporter::ReadGrou_Binary(COB::Scene& out, StreamReaderLE& reader, const const chunk_guard cn(nfo,reader); - out.nodes.push_back(std::shared_ptr(new Group())); + out.nodes.push_back(std::make_shared()); Group& msh = (Group&)(*out.nodes.back().get()); msh = nfo; diff --git a/third_party/libassimp/code/COBLoader.h b/third_party/libassimp/code/COB/COBLoader.h similarity index 99% rename from third_party/libassimp/code/COBLoader.h rename to third_party/libassimp/code/COB/COBLoader.h index 156c8d9114..40fed324ba 100644 --- a/third_party/libassimp/code/COBLoader.h +++ b/third_party/libassimp/code/COB/COBLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/COBScene.h b/third_party/libassimp/code/COB/COBScene.h similarity index 99% rename from third_party/libassimp/code/COBScene.h rename to third_party/libassimp/code/COB/COBScene.h index 2473c42a57..90349be702 100644 --- a/third_party/libassimp/code/COBScene.h +++ b/third_party/libassimp/code/COB/COBScene.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/CSMLoader.cpp b/third_party/libassimp/code/CSM/CSMLoader.cpp similarity index 99% rename from third_party/libassimp/code/CSMLoader.cpp rename to third_party/libassimp/code/CSM/CSMLoader.cpp index 777b6cf1ba..9dbb384678 100644 --- a/third_party/libassimp/code/CSMLoader.cpp +++ b/third_party/libassimp/code/CSM/CSMLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/CSMLoader.h b/third_party/libassimp/code/CSM/CSMLoader.h similarity index 98% rename from third_party/libassimp/code/CSMLoader.h rename to third_party/libassimp/code/CSM/CSMLoader.h index ea82bb87a6..31a814b521 100644 --- a/third_party/libassimp/code/CSMLoader.h +++ b/third_party/libassimp/code/CSM/CSMLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/ColladaExporter.cpp b/third_party/libassimp/code/Collada/ColladaExporter.cpp similarity index 94% rename from third_party/libassimp/code/ColladaExporter.cpp rename to third_party/libassimp/code/Collada/ColladaExporter.cpp index 96421a5325..6fd31ed3b4 100644 --- a/third_party/libassimp/code/ColladaExporter.cpp +++ b/third_party/libassimp/code/Collada/ColladaExporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -45,6 +45,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "ColladaExporter.h" #include +#include #include #include #include @@ -64,13 +65,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using namespace Assimp; -namespace Assimp -{ +namespace Assimp { // ------------------------------------------------------------------------------------------------ // Worker function for exporting a scene to Collada. Prototyped and registered in Exporter.cpp -void ExportSceneCollada(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* /*pProperties*/) -{ +void ExportSceneCollada(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* /*pProperties*/) { std::string path = DefaultIOSystem::absolutePath(std::string(pFile)); std::string file = DefaultIOSystem::completeBaseName(std::string(pFile)); @@ -93,15 +92,15 @@ void ExportSceneCollada(const char* pFile, IOSystem* pIOSystem, const aiScene* p } // end of namespace Assimp - - // ------------------------------------------------------------------------------------------------ // Constructor for a specific scene to export -ColladaExporter::ColladaExporter( const aiScene* pScene, IOSystem* pIOSystem, const std::string& path, const std::string& file) : mIOSystem(pIOSystem), mPath(path), mFile(file) -{ +ColladaExporter::ColladaExporter( const aiScene* pScene, IOSystem* pIOSystem, const std::string& path, const std::string& file) +: mIOSystem(pIOSystem) +, mPath(path) +, mFile(file) { // make sure that all formatting happens using the standard, C locale and not the user's current locale mOutput.imbue( std::locale("C") ); - mOutput.precision(16); + mOutput.precision(ASSIMP_AI_REAL_TEXT_PRECISION); mScene = pScene; mSceneOwned = false; @@ -115,17 +114,15 @@ ColladaExporter::ColladaExporter( const aiScene* pScene, IOSystem* pIOSystem, co // ------------------------------------------------------------------------------------------------ // Destructor -ColladaExporter::~ColladaExporter() -{ - if(mSceneOwned) { +ColladaExporter::~ColladaExporter() { + if ( mSceneOwned ) { delete mScene; } } // ------------------------------------------------------------------------------------------------ // Starts writing the contents -void ColladaExporter::WriteFile() -{ +void ColladaExporter::WriteFile() { // write the DTD mOutput << "" << endstr; // COLLADA element start @@ -158,9 +155,8 @@ void ColladaExporter::WriteFile() // ------------------------------------------------------------------------------------------------ // Writes the asset header -void ColladaExporter::WriteHeader() -{ - static const ai_real epsilon = ai_real( 0.00001 ); +void ColladaExporter::WriteHeader() { + static const ai_real epsilon = Math::getEpsilon(); static const aiQuaternion x_rot(aiMatrix3x3( 0, -1, 0, 1, 0, 0, @@ -238,25 +234,64 @@ void ColladaExporter::WriteHeader() mOutput << startstr << "" << endstr; PushTag(); - aiMetadata* meta = mScene->mRootNode->mMetaData; + // If no Scene metadata, use root node metadata + aiMetadata* meta = mScene->mMetaData; + if (nullptr == meta) { + meta = mScene->mRootNode->mMetaData; + } + aiString value; - if (!meta || !meta->Get("Author", value)) + if (!meta || !meta->Get("Author", value)) { mOutput << startstr << "" << "Assimp" << "" << endstr; - else + } else { mOutput << startstr << "" << XMLEscape(value.C_Str()) << "" << endstr; + } - if (!meta || !meta->Get("AuthoringTool", value)) + if (nullptr == meta || !meta->Get("AuthoringTool", value)) { mOutput << startstr << "" << "Assimp Exporter" << "" << endstr; - else + } else { mOutput << startstr << "" << XMLEscape(value.C_Str()) << "" << endstr; + } - //mOutput << startstr << "" << mScene->author.C_Str() << "" << endstr; - //mOutput << startstr << "" << mScene->authoringTool.C_Str() << "" << endstr; + if (meta) { + if (meta->Get("Comments", value)) { + mOutput << startstr << "" << XMLEscape(value.C_Str()) << "" << endstr; + } + if (meta->Get("Copyright", value)) { + mOutput << startstr << "" << XMLEscape(value.C_Str()) << "" << endstr; + } + if (meta->Get("SourceData", value)) { + mOutput << startstr << "" << XMLEscape(value.C_Str()) << "" << endstr; + } + } PopTag(); mOutput << startstr << "" << endstr; - mOutput << startstr << "" << date_str << "" << endstr; + + if (nullptr == meta || !meta->Get("Created", value)) { + mOutput << startstr << "" << date_str << "" << endstr; + } else { + mOutput << startstr << "" << XMLEscape(value.C_Str()) << "" << endstr; + } + + // Modified date is always the date saved mOutput << startstr << "" << date_str << "" << endstr; + + if (meta) { + if (meta->Get("Keywords", value)) { + mOutput << startstr << "" << XMLEscape(value.C_Str()) << "" << endstr; + } + if (meta->Get("Revision", value)) { + mOutput << startstr << "" << XMLEscape(value.C_Str()) << "" << endstr; + } + if (meta->Get("Subject", value)) { + mOutput << startstr << "" << XMLEscape(value.C_Str()) << "" << endstr; + } + if (meta->Get("Title", value)) { + mOutput << startstr << "" << XMLEscape(value.C_Str()) << "" << endstr; + } + } + mOutput << startstr << "" << endstr; mOutput << startstr << "" << up_axis << "" << endstr; PopTag(); @@ -269,18 +304,21 @@ void ColladaExporter::WriteTextures() { static const unsigned int buffer_size = 1024; char str[buffer_size]; - if(mScene->HasTextures()) { + if (mScene->HasTextures()) { for(unsigned int i = 0; i < mScene->mNumTextures; i++) { // It would be great to be able to create a directory in portable standard C++, but it's not the case, // so we just write the textures in the current directory. aiTexture* texture = mScene->mTextures[i]; + if ( nullptr == texture ) { + continue; + } ASSIMP_itoa10(str, buffer_size, i + 1); std::string name = mFile + "_texture_" + (i < 1000 ? "0" : "") + (i < 100 ? "0" : "") + (i < 10 ? "0" : "") + str + "." + ((const char*) texture->achFormatHint); - std::unique_ptr outfile(mIOSystem->Open(mPath + name, "wb")); + std::unique_ptr outfile(mIOSystem->Open(mPath + mIOSystem->getOsSeparator() + name, "wb")); if(outfile == NULL) { throw DeadlyExportError("could not open output texture file: " + mPath + name); } @@ -428,6 +466,7 @@ void ColladaExporter::WritePointLight(const aiLight *const light){ mOutput << startstr << "" << endstr; } + void ColladaExporter::WriteDirectionalLight(const aiLight *const light){ const aiColor3D &color= light->mColorDiffuse; mOutput << startstr << "" << endstr; @@ -440,6 +479,7 @@ void ColladaExporter::WriteDirectionalLight(const aiLight *const light){ mOutput << startstr << "" << endstr; } + void ColladaExporter::WriteSpotLight(const aiLight *const light){ const aiColor3D &color= light->mColorDiffuse; @@ -496,18 +536,16 @@ void ColladaExporter::WriteAmbienttLight(const aiLight *const light){ // ------------------------------------------------------------------------------------------------ // Reads a single surface entry from the given material keys -void ColladaExporter::ReadMaterialSurface( Surface& poSurface, const aiMaterial* pSrcMat, aiTextureType pTexture, const char* pKey, size_t pType, size_t pIndex) -{ - if( pSrcMat->GetTextureCount( pTexture) > 0 ) - { +void ColladaExporter::ReadMaterialSurface( Surface& poSurface, const aiMaterial* pSrcMat, + aiTextureType pTexture, const char* pKey, size_t pType, size_t pIndex) { + if( pSrcMat->GetTextureCount( pTexture) > 0 ) { aiString texfile; unsigned int uvChannel = 0; pSrcMat->GetTexture( pTexture, 0, &texfile, NULL, &uvChannel); std::string index_str(texfile.C_Str()); - if(index_str.size() != 0 && index_str[0] == '*') - { + if(index_str.size() != 0 && index_str[0] == '*') { unsigned int index; index_str = index_str.substr(1, std::string::npos); @@ -525,15 +563,13 @@ void ColladaExporter::ReadMaterialSurface( Surface& poSurface, const aiMaterial* } else { throw DeadlyExportError("could not find embedded texture at index " + index_str); } - } else - { + } else { poSurface.texture = texfile.C_Str(); } poSurface.channel = uvChannel; poSurface.exist = true; - } else - { + } else { if( pKey ) poSurface.exist = pSrcMat->Get( pKey, static_cast(pType), static_cast(pIndex), poSurface.color) == aiReturn_SUCCESS; } @@ -541,15 +577,13 @@ void ColladaExporter::ReadMaterialSurface( Surface& poSurface, const aiMaterial* // ------------------------------------------------------------------------------------------------ // Reimplementation of isalnum(,C locale), because AppVeyor does not see standard version. -static bool isalnum_C(char c) -{ +static bool isalnum_C(char c) { return ( nullptr != strchr("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",c) ); } // ------------------------------------------------------------------------------------------------ // Writes an image entry for the given surface -void ColladaExporter::WriteImageEntry( const Surface& pSurface, const std::string& pNameAdd) -{ +void ColladaExporter::WriteImageEntry( const Surface& pSurface, const std::string& pNameAdd) { if( !pSurface.texture.empty() ) { mOutput << startstr << "" << endstr; @@ -803,8 +837,9 @@ void ColladaExporter::WriteControllerLibrary() mOutput << startstr << "" << endstr; PushTag(); - for( size_t a = 0; a < mScene->mNumMeshes; ++a) + for( size_t a = 0; a < mScene->mNumMeshes; ++a) { WriteController( a); + } PopTag(); mOutput << startstr << "" << endstr; @@ -1500,24 +1535,18 @@ void ColladaExporter::WriteNode( const aiScene* pScene, aiNode* pNode) // otherwise it is a normal node (NODE) const char * node_type; bool is_joint, is_skeleton_root = false; - if (NULL == findBone(pScene, pNode->mName.C_Str())) { + if (nullptr == findBone(pScene, pNode->mName.C_Str())) { node_type = "NODE"; is_joint = false; } else { node_type = "JOINT"; is_joint = true; - if(!pNode->mParent || NULL == findBone(pScene, pNode->mParent->mName.C_Str())) + if (!pNode->mParent || nullptr == findBone(pScene, pNode->mParent->mName.C_Str())) { is_skeleton_root = true; + } } const std::string node_name_escaped = XMLEscape(pNode->mName.data); - /* // customized, Note! the id field is crucial for inter-xml look up, it cannot be replaced with sid ?! - mOutput << startstr - << "mTransformation; + aiMatrix4x4 mat = pNode->mTransformation; + + // If this node is a Camera node, the camera coordinate system needs to be multiplied in. + // When importing from Collada, the mLookAt is set to 0, 0, -1, and the node transform is unchanged. + // When importing from a different format, mLookAt is set to 0, 0, 1. Therefore, the local camera + // coordinate system must be changed to matche the Collada specification. + for (size_t i = 0; imNumCameras; i++){ + if (mScene->mCameras[i]->mName == pNode->mName){ + aiMatrix4x4 sourceView; + mScene->mCameras[i]->GetCameraMatrix(sourceView); + + aiMatrix4x4 colladaView; + colladaView.a1 = colladaView.c3 = -1; // move into -z space. + mat *= (sourceView * colladaView); + break; + } + } // customized, sid should be 'matrix' to match with loader code. //mOutput << startstr << ""; diff --git a/third_party/libassimp/code/ColladaExporter.h b/third_party/libassimp/code/Collada/ColladaExporter.h similarity index 99% rename from third_party/libassimp/code/ColladaExporter.h rename to third_party/libassimp/code/Collada/ColladaExporter.h index d1a307532c..0b4fa59a3d 100644 --- a/third_party/libassimp/code/ColladaExporter.h +++ b/third_party/libassimp/code/Collada/ColladaExporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -150,7 +150,6 @@ public: /// Stringstream to write all output into std::stringstream mOutput; -protected: /// The IOSystem for output IOSystem* mIOSystem; @@ -204,7 +203,7 @@ protected: std::map textures; -protected: +public: /// Dammit C++ - y u no compile two-pass? No I have to add all methods below the struct definitions /// Reads a single surface entry from the given material keys void ReadMaterialSurface( Surface& poSurface, const aiMaterial* pSrcMat, aiTextureType pTexture, const char* pKey, size_t pType, size_t pIndex); diff --git a/third_party/libassimp/code/ColladaHelper.h b/third_party/libassimp/code/Collada/ColladaHelper.h similarity index 98% rename from third_party/libassimp/code/ColladaHelper.h rename to third_party/libassimp/code/Collada/ColladaHelper.h index fe6674b933..66cff2d207 100644 --- a/third_party/libassimp/code/ColladaHelper.h +++ b/third_party/libassimp/code/Collada/ColladaHelper.h @@ -4,7 +4,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -580,15 +580,11 @@ struct Image { std::string mFileName; - /** If image file name is zero, embedded image data - */ + /** Embedded image data */ std::vector mImageData; - /** If image file name is zero, file format of - * embedded image data. - */ + /** File format hint ofembedded image data */ std::string mEmbeddedFormat; - }; /** An animation channel. */ diff --git a/third_party/libassimp/code/ColladaLoader.cpp b/third_party/libassimp/code/Collada/ColladaLoader.cpp similarity index 58% rename from third_party/libassimp/code/ColladaLoader.cpp rename to third_party/libassimp/code/Collada/ColladaLoader.cpp index d86985a29a..0fbc7d599d 100644 --- a/third_party/libassimp/code/ColladaLoader.cpp +++ b/third_party/libassimp/code/Collada/ColladaLoader.cpp @@ -3,9 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team - - +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -43,7 +41,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** @file Implementation of the Collada loader */ - #ifndef ASSIMP_BUILD_NO_COLLADA_IMPORTER #include "ColladaLoader.h" @@ -60,13 +57,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include +#include #include "time.h" #include "math.h" #include #include +#include -using namespace Assimp; +namespace Assimp { + using namespace Assimp::Formatter; static const aiImporterDesc desc = { @@ -74,78 +74,92 @@ static const aiImporterDesc desc = { "", "", "http://collada.org", - aiImporterFlags_SupportTextFlavour, + aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportCompressedFlavour, 1, 3, 1, 5, - "dae" + "dae zae" }; // ------------------------------------------------------------------------------------------------ // Constructor to be privately used by Importer ColladaLoader::ColladaLoader() : mFileName() - , mMeshIndexByID() - , mMaterialIndexByName() - , mMeshes() - , newMats() - , mCameras() - , mLights() - , mTextures() - , mAnims() - , noSkeletonMesh( false ) + , mMeshIndexByID() + , mMaterialIndexByName() + , mMeshes() + , newMats() + , mCameras() + , mLights() + , mTextures() + , mAnims() + , noSkeletonMesh(false) , ignoreUpDirection(false) - , mNodeNameCounter( 0 ) -{} + , useColladaName(false) + , mNodeNameCounter(0) { + // empty +} // ------------------------------------------------------------------------------------------------ // Destructor, private as well -ColladaLoader::~ColladaLoader() -{} +ColladaLoader::~ColladaLoader() { + // empty +} // ------------------------------------------------------------------------------------------------ // Returns whether the class can handle the format of the given file. -bool ColladaLoader::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const -{ +bool ColladaLoader::CanRead(const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const { // check file extension - std::string extension = GetExtension(pFile); + const std::string extension = GetExtension(pFile); - if( extension == "dae") - return true; + bool readSig = checkSig && (pIOHandler != nullptr); + + if (!readSig) { + if (extension == "dae" || extension == "zae") { + return true; + } + } + + if (readSig) { + // Look for a DAE file inside, but don't extract it + ZipArchiveIOSystem zip_archive(pIOHandler, pFile); + if (zip_archive.isOpen()) + return !ColladaParser::ReadZaeManifest(zip_archive).empty(); + } // XML - too generic, we need to open the file and search for typical keywords - if( extension == "xml" || !extension.length() || checkSig) { + if (extension == "xml" || !extension.length() || checkSig) { /* If CanRead() is called in order to check whether we * support a specific file extension in general pIOHandler * might be NULL and it's our duty to return true here. */ - if (!pIOHandler)return true; - const char* tokens[] = {"GetPropertyInteger(AI_CONFIG_IMPORT_NO_SKELETON_MESHES,0) != 0; - ignoreUpDirection = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_COLLADA_IGNORE_UP_DIRECTION,0) != 0; - useColladaName = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_COLLADA_USE_COLLADA_NAMES,0) != 0; +void ColladaLoader::SetupProperties(const Importer* pImp) { + noSkeletonMesh = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, 0) != 0; + ignoreUpDirection = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_COLLADA_IGNORE_UP_DIRECTION, 0) != 0; + useColladaName = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_COLLADA_USE_COLLADA_NAMES, 0) != 0; } // ------------------------------------------------------------------------------------------------ // Get file extension list -const aiImporterDesc* ColladaLoader::GetInfo () const -{ +const aiImporterDesc* ColladaLoader::GetInfo() const { return &desc; } // ------------------------------------------------------------------------------------------------ // Imports the given file into the given scene structure. -void ColladaLoader::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) -{ +void ColladaLoader::InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) { mFileName = pFile; // clean all member arrays - just for safety, it should work even if we did not @@ -160,66 +174,82 @@ void ColladaLoader::InternReadFile( const std::string& pFile, aiScene* pScene, I mAnims.clear(); // parse the input file - ColladaParser parser( pIOHandler, pFile); + ColladaParser parser(pIOHandler, pFile); - if( !parser.mRootNode) + + if( !parser.mRootNode) { throw DeadlyImportError( "Collada: File came out empty. Something is wrong here."); + } // reserve some storage to avoid unnecessary reallocs - newMats.reserve(parser.mMaterialLibrary.size()*2); - mMeshes.reserve(parser.mMeshLibrary.size()*2); + newMats.reserve(parser.mMaterialLibrary.size()*2u); + mMeshes.reserve(parser.mMeshLibrary.size()*2u); mCameras.reserve(parser.mCameraLibrary.size()); mLights.reserve(parser.mLightLibrary.size()); // create the materials first, for the meshes to find - BuildMaterials( parser, pScene); + BuildMaterials(parser, pScene); // build the node hierarchy from it - pScene->mRootNode = BuildHierarchy( parser, parser.mRootNode); + pScene->mRootNode = BuildHierarchy(parser, parser.mRootNode); // ... then fill the materials with the now adjusted settings FillMaterials(parser, pScene); - // Apply unitsize scale calculation + // Apply unit-size scale calculation + pScene->mRootNode->mTransformation *= aiMatrix4x4(parser.mUnitSize, 0, 0, 0, 0, parser.mUnitSize, 0, 0, 0, 0, parser.mUnitSize, 0, 0, 0, 0, 1); if( !ignoreUpDirection ) { - // Convert to Y_UP, if different orientation - if( parser.mUpDirection == ColladaParser::UP_X) - pScene->mRootNode->mTransformation *= aiMatrix4x4( - 0, -1, 0, 0, - 1, 0, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1); - else if( parser.mUpDirection == ColladaParser::UP_Z) - pScene->mRootNode->mTransformation *= aiMatrix4x4( - 1, 0, 0, 0, - 0, 0, 1, 0, - 0, -1, 0, 0, - 0, 0, 0, 1); + // Convert to Y_UP, if different orientation + if( parser.mUpDirection == ColladaParser::UP_X) { + pScene->mRootNode->mTransformation *= aiMatrix4x4( + 0, -1, 0, 0, + 1, 0, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1); + } else if( parser.mUpDirection == ColladaParser::UP_Z) { + pScene->mRootNode->mTransformation *= aiMatrix4x4( + 1, 0, 0, 0, + 0, 0, 1, 0, + 0, -1, 0, 0, + 0, 0, 0, 1); + } + } + + // Store scene metadata + if (!parser.mAssetMetaData.empty()) { + const size_t numMeta(parser.mAssetMetaData.size()); + pScene->mMetaData = aiMetadata::Alloc(static_cast(numMeta)); + size_t i = 0; + for (auto it = parser.mAssetMetaData.cbegin(); it != parser.mAssetMetaData.cend(); ++it, ++i) { + pScene->mMetaData->Set(static_cast(i), (*it).first, (*it).second); + } } // store all meshes - StoreSceneMeshes( pScene); + StoreSceneMeshes(pScene); // store all materials - StoreSceneMaterials( pScene); + StoreSceneMaterials(pScene); + + // store all textures + StoreSceneTextures(pScene); // store all lights - StoreSceneLights( pScene); + StoreSceneLights(pScene); // store all cameras - StoreSceneCameras( pScene); + StoreSceneCameras(pScene); // store all animations - StoreAnimations( pScene, parser); - + StoreAnimations(pScene, parser); // If no meshes have been loaded, it's probably just an animated skeleton. - if (!pScene->mNumMeshes) { + if ( 0u == pScene->mNumMeshes) { if (!noSkeletonMesh) { SkeletonMeshBuilder hero(pScene); @@ -230,60 +260,56 @@ void ColladaLoader::InternReadFile( const std::string& pFile, aiScene* pScene, I // ------------------------------------------------------------------------------------------------ // Recursively constructs a scene node for the given parser node and returns it. -aiNode* ColladaLoader::BuildHierarchy( const ColladaParser& pParser, const Collada::Node* pNode) -{ +aiNode* ColladaLoader::BuildHierarchy(const ColladaParser& pParser, const Collada::Node* pNode) { // create a node for it aiNode* node = new aiNode(); // find a name for the new node. It's more complicated than you might think - node->mName.Set( FindNameForNode( pNode)); + node->mName.Set(FindNameForNode(pNode)); // calculate the transformation matrix for it - node->mTransformation = pParser.CalculateResultTransform( pNode->mTransforms); + node->mTransformation = pParser.CalculateResultTransform(pNode->mTransforms); // now resolve node instances std::vector instances; - ResolveNodeInstances(pParser,pNode,instances); + ResolveNodeInstances(pParser, pNode, instances); // add children. first the *real* ones - node->mNumChildren = static_cast(pNode->mChildren.size()+instances.size()); + node->mNumChildren = static_cast(pNode->mChildren.size() + instances.size()); node->mChildren = new aiNode*[node->mNumChildren]; - for( size_t a = 0; a < pNode->mChildren.size(); a++) - { - node->mChildren[a] = BuildHierarchy( pParser, pNode->mChildren[a]); + for (size_t a = 0; a < pNode->mChildren.size(); ++a) { + node->mChildren[a] = BuildHierarchy(pParser, pNode->mChildren[a]); node->mChildren[a]->mParent = node; } // ... and finally the resolved node instances - for( size_t a = 0; a < instances.size(); a++) - { - node->mChildren[pNode->mChildren.size() + a] = BuildHierarchy( pParser, instances[a]); + for (size_t a = 0; a < instances.size(); ++a) { + node->mChildren[pNode->mChildren.size() + a] = BuildHierarchy(pParser, instances[a]); node->mChildren[pNode->mChildren.size() + a]->mParent = node; } // construct meshes - BuildMeshesForNode( pParser, pNode, node); + BuildMeshesForNode(pParser, pNode, node); // construct cameras BuildCamerasForNode(pParser, pNode, node); // construct lights BuildLightsForNode(pParser, pNode, node); + return node; } // ------------------------------------------------------------------------------------------------ // Resolve node instances -void ColladaLoader::ResolveNodeInstances( const ColladaParser& pParser, const Collada::Node* pNode, - std::vector& resolved) -{ +void ColladaLoader::ResolveNodeInstances(const ColladaParser& pParser, const Collada::Node* pNode, + std::vector& resolved) { // reserve enough storage resolved.reserve(pNode->mNodeInstances.size()); // ... and iterate through all nodes to be instanced as children of pNode - for (const auto &nodeInst: pNode->mNodeInstances) - { + for (const auto &nodeInst : pNode->mNodeInstances) { // find the corresponding node in the library const ColladaParser::NodeLibrary::const_iterator itt = pParser.mNodeLibrary.find(nodeInst.mNode); const Collada::Node* nd = itt == pParser.mNodeLibrary.end() ? NULL : (*itt).second; @@ -291,13 +317,12 @@ void ColladaLoader::ResolveNodeInstances( const ColladaParser& pParser, const Co // FIX for http://sourceforge.net/tracker/?func=detail&aid=3054873&group_id=226462&atid=1067632 // need to check for both name and ID to catch all. To avoid breaking valid files, // the workaround is only enabled when the first attempt to resolve the node has failed. - if (!nd) { + if (nullptr == nd) { nd = FindNode(pParser.mRootNode, nodeInst.mNode); } - if (!nd) + if (nullptr == nd) { ASSIMP_LOG_ERROR_F("Collada: Unable to resolve reference to instanced node ", nodeInst.mNode); - - else { + } else { // attach this node to the list of children resolved.push_back(nd); } @@ -307,12 +332,13 @@ void ColladaLoader::ResolveNodeInstances( const ColladaParser& pParser, const Co // ------------------------------------------------------------------------------------------------ // Resolve UV channels void ColladaLoader::ApplyVertexToEffectSemanticMapping(Collada::Sampler& sampler, - const Collada::SemanticMappingTable& table) -{ + + const Collada::SemanticMappingTable& table) { std::map::const_iterator it = table.mMap.find(sampler.mUVChannel); if (it != table.mMap.end()) { - if (it->second.mType != Collada::IT_Texcoord) + if (it->second.mType != Collada::IT_Texcoord) { ASSIMP_LOG_ERROR("Collada: Unexpected effect input mapping"); + } sampler.mUVId = it->second.mSet; } @@ -320,15 +346,12 @@ void ColladaLoader::ApplyVertexToEffectSemanticMapping(Collada::Sampler& sampler // ------------------------------------------------------------------------------------------------ // Builds lights for the given node and references them -void ColladaLoader::BuildLightsForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget) -{ - for( const Collada::LightInstance& lid : pNode->mLights) - { +void ColladaLoader::BuildLightsForNode(const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget) { + for (const Collada::LightInstance& lid : pNode->mLights) { // find the referred light - ColladaParser::LightLibrary::const_iterator srcLightIt = pParser.mLightLibrary.find( lid.mLight); - if( srcLightIt == pParser.mLightLibrary.end()) - { - ASSIMP_LOG_WARN_F("Collada: Unable to find light for ID \"" , lid.mLight , "\". Skipping."); + ColladaParser::LightLibrary::const_iterator srcLightIt = pParser.mLightLibrary.find(lid.mLight); + if (srcLightIt == pParser.mLightLibrary.end()) { + ASSIMP_LOG_WARN_F("Collada: Unable to find light for ID \"", lid.mLight, "\". Skipping."); continue; } const Collada::Light* srcLight = &srcLightIt->second; @@ -339,7 +362,7 @@ void ColladaLoader::BuildLightsForNode( const ColladaParser& pParser, const Coll out->mType = (aiLightSourceType)srcLight->mType; // collada lights point in -Z by default, rest is specified in node transform - out->mDirection = aiVector3D(0.f,0.f,-1.f); + out->mDirection = aiVector3D(0.f, 0.f, -1.f); out->mAttenuationConstant = srcLight->mAttConstant; out->mAttenuationLinear = srcLight->mAttLinear; @@ -358,27 +381,26 @@ void ColladaLoader::BuildLightsForNode( const ColladaParser& pParser, const Coll // convert falloff angle and falloff exponent in our representation, if given if (out->mType == aiLightSource_SPOT) { - - out->mAngleInnerCone = AI_DEG_TO_RAD( srcLight->mFalloffAngle ); + out->mAngleInnerCone = AI_DEG_TO_RAD(srcLight->mFalloffAngle); // ... some extension magic. - if (srcLight->mOuterAngle >= ASSIMP_COLLADA_LIGHT_ANGLE_NOT_SET*(1-1e-6f)) - { + if (srcLight->mOuterAngle >= ASSIMP_COLLADA_LIGHT_ANGLE_NOT_SET * (1 - 1e-6f)) { // ... some deprecation magic. - if (srcLight->mPenumbraAngle >= ASSIMP_COLLADA_LIGHT_ANGLE_NOT_SET*(1-1e-6f)) - { + if (srcLight->mPenumbraAngle >= ASSIMP_COLLADA_LIGHT_ANGLE_NOT_SET * (1 - 1e-6f)) { // Need to rely on falloff_exponent. I don't know how to interpret it, so I need to guess .... // epsilon chosen to be 0.1 - out->mAngleOuterCone = std::acos(std::pow(0.1f,1.f/srcLight->mFalloffExponent))+ - out->mAngleInnerCone; + out->mAngleOuterCone = std::acos(std::pow(0.1f, 1.f / srcLight->mFalloffExponent)) + + out->mAngleInnerCone; } else { - out->mAngleOuterCone = out->mAngleInnerCone + AI_DEG_TO_RAD( srcLight->mPenumbraAngle ); + out->mAngleOuterCone = out->mAngleInnerCone + AI_DEG_TO_RAD(srcLight->mPenumbraAngle); if (out->mAngleOuterCone < out->mAngleInnerCone) - std::swap(out->mAngleInnerCone,out->mAngleOuterCone); + std::swap(out->mAngleInnerCone, out->mAngleOuterCone); } } - else out->mAngleOuterCone = AI_DEG_TO_RAD( srcLight->mOuterAngle ); + else { + out->mAngleOuterCone = AI_DEG_TO_RAD(srcLight->mOuterAngle); + } } // add to light list @@ -388,15 +410,12 @@ void ColladaLoader::BuildLightsForNode( const ColladaParser& pParser, const Coll // ------------------------------------------------------------------------------------------------ // Builds cameras for the given node and references them -void ColladaLoader::BuildCamerasForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget) -{ - for( const Collada::CameraInstance& cid : pNode->mCameras) - { +void ColladaLoader::BuildCamerasForNode(const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget) { + for (const Collada::CameraInstance& cid : pNode->mCameras) { // find the referred light - ColladaParser::CameraLibrary::const_iterator srcCameraIt = pParser.mCameraLibrary.find( cid.mCamera); - if( srcCameraIt == pParser.mCameraLibrary.end()) - { - ASSIMP_LOG_WARN_F("Collada: Unable to find camera for ID \"" , cid.mCamera , "\". Skipping."); + ColladaParser::CameraLibrary::const_iterator srcCameraIt = pParser.mCameraLibrary.find(cid.mCamera); + if (srcCameraIt == pParser.mCameraLibrary.end()) { + ASSIMP_LOG_WARN_F("Collada: Unable to find camera for ID \"", cid.mCamera, "\". Skipping."); continue; } const Collada::Camera* srcCamera = &srcCameraIt->second; @@ -411,7 +430,7 @@ void ColladaLoader::BuildCamerasForNode( const ColladaParser& pParser, const Col out->mName = pTarget->mName; // collada cameras point in -Z by default, rest is specified in node transform - out->mLookAt = aiVector3D(0.f,0.f,-1.f); + out->mLookAt = aiVector3D(0.f, 0.f, -1.f); // near/far z is already ok out->mClipPlaneFar = srcCamera->mZFar; @@ -419,8 +438,9 @@ void ColladaLoader::BuildCamerasForNode( const ColladaParser& pParser, const Col // ... but for the rest some values are optional // and we need to compute the others in any combination. - if (srcCamera->mAspect != 10e10f) + if (srcCamera->mAspect != 10e10f) { out->mAspect = srcCamera->mAspect; + } if (srcCamera->mHorFov != 10e10f) { out->mHorizontalFOV = srcCamera->mHorFov; @@ -429,8 +449,8 @@ void ColladaLoader::BuildCamerasForNode( const ColladaParser& pParser, const Col out->mAspect = std::tan(AI_DEG_TO_RAD(srcCamera->mHorFov)) / 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(std::atan(srcCamera->mAspect * std::tan(AI_DEG_TO_RAD(srcCamera->mVerFov) * 0.5f))); } @@ -445,206 +465,194 @@ void ColladaLoader::BuildCamerasForNode( const ColladaParser& pParser, const Col // ------------------------------------------------------------------------------------------------ // Builds meshes for the given node and references them -void ColladaLoader::BuildMeshesForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget) -{ +void ColladaLoader::BuildMeshesForNode(const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget) { // accumulated mesh references by this node std::vector newMeshRefs; newMeshRefs.reserve(pNode->mMeshes.size()); // add a mesh for each subgroup in each collada mesh - for( const Collada::MeshInstance& mid : pNode->mMeshes) - { - const Collada::Mesh* srcMesh = NULL; - const Collada::Controller* srcController = NULL; + for (const Collada::MeshInstance& mid : pNode->mMeshes) { + const Collada::Mesh* srcMesh = nullptr; + const Collada::Controller* srcController = nullptr; // find the referred mesh - ColladaParser::MeshLibrary::const_iterator srcMeshIt = pParser.mMeshLibrary.find( mid.mMeshOrController); - if( srcMeshIt == pParser.mMeshLibrary.end()) - { + ColladaParser::MeshLibrary::const_iterator srcMeshIt = pParser.mMeshLibrary.find(mid.mMeshOrController); + if (srcMeshIt == pParser.mMeshLibrary.end()) { // if not found in the mesh-library, it might also be a controller referring to a mesh - ColladaParser::ControllerLibrary::const_iterator srcContrIt = pParser.mControllerLibrary.find( mid.mMeshOrController); - if( srcContrIt != pParser.mControllerLibrary.end()) - { + ColladaParser::ControllerLibrary::const_iterator srcContrIt = pParser.mControllerLibrary.find(mid.mMeshOrController); + if (srcContrIt != pParser.mControllerLibrary.end()) { srcController = &srcContrIt->second; - srcMeshIt = pParser.mMeshLibrary.find( srcController->mMeshId); - if( srcMeshIt != pParser.mMeshLibrary.end()) + srcMeshIt = pParser.mMeshLibrary.find(srcController->mMeshId); + if (srcMeshIt != pParser.mMeshLibrary.end()) { srcMesh = srcMeshIt->second; + } } - if( !srcMesh) - { + + if( nullptr == srcMesh) { ASSIMP_LOG_WARN_F( "Collada: Unable to find geometry for ID \"", mid.mMeshOrController, "\". Skipping." ); continue; } - } else - { + } + else { // ID found in the mesh library -> direct reference to an unskinned mesh srcMesh = srcMeshIt->second; } // build a mesh for each of its subgroups size_t vertexStart = 0, faceStart = 0; - for( size_t sm = 0; sm < srcMesh->mSubMeshes.size(); ++sm) - { + for (size_t sm = 0; sm < srcMesh->mSubMeshes.size(); ++sm) { const Collada::SubMesh& submesh = srcMesh->mSubMeshes[sm]; - if( submesh.mNumFaces == 0) + if (submesh.mNumFaces == 0) { continue; + } // find material assigned to this submesh std::string meshMaterial; - std::map::const_iterator meshMatIt = mid.mMaterials.find( submesh.mMaterial); + std::map::const_iterator meshMatIt = mid.mMaterials.find(submesh.mMaterial); - const Collada::SemanticMappingTable* table = NULL; - if( meshMatIt != mid.mMaterials.end()) - { + const Collada::SemanticMappingTable* table = nullptr; + if (meshMatIt != mid.mMaterials.end()) { table = &meshMatIt->second; meshMaterial = table->mMatName; } - else - { - ASSIMP_LOG_WARN_F( "Collada: No material specified for subgroup <", submesh.mMaterial, "> in geometry <", - mid.mMeshOrController, ">." ); - if( !mid.mMaterials.empty() ) + else { + ASSIMP_LOG_WARN_F("Collada: No material specified for subgroup <", submesh.mMaterial, "> in geometry <", + mid.mMeshOrController, ">."); + if (!mid.mMaterials.empty()) { meshMaterial = mid.mMaterials.begin()->second.mMatName; + } } // OK ... here the *real* fun starts ... we have the vertex-input-to-effect-semantic-table // given. The only mapping stuff which we do actually support is the UV channel. - std::map::const_iterator matIt = mMaterialIndexByName.find( meshMaterial); - unsigned int matIdx; - if( matIt != mMaterialIndexByName.end()) + std::map::const_iterator matIt = mMaterialIndexByName.find(meshMaterial); + unsigned int matIdx = 0; + if (matIt != mMaterialIndexByName.end()) { matIdx = static_cast(matIt->second); - else - matIdx = 0; + } - if (table && !table->mMap.empty() ) { + if (table && !table->mMap.empty()) { std::pair& mat = newMats[matIdx]; // Iterate through all texture channels assigned to the effect and // check whether we have mapping information for it. - ApplyVertexToEffectSemanticMapping(mat.first->mTexDiffuse, *table); - ApplyVertexToEffectSemanticMapping(mat.first->mTexAmbient, *table); - ApplyVertexToEffectSemanticMapping(mat.first->mTexSpecular, *table); - ApplyVertexToEffectSemanticMapping(mat.first->mTexEmissive, *table); - ApplyVertexToEffectSemanticMapping(mat.first->mTexTransparent,*table); - ApplyVertexToEffectSemanticMapping(mat.first->mTexBump, *table); + ApplyVertexToEffectSemanticMapping(mat.first->mTexDiffuse, *table); + ApplyVertexToEffectSemanticMapping(mat.first->mTexAmbient, *table); + ApplyVertexToEffectSemanticMapping(mat.first->mTexSpecular, *table); + ApplyVertexToEffectSemanticMapping(mat.first->mTexEmissive, *table); + ApplyVertexToEffectSemanticMapping(mat.first->mTexTransparent, *table); + ApplyVertexToEffectSemanticMapping(mat.first->mTexBump, *table); } // built lookup index of the Mesh-Submesh-Material combination - ColladaMeshIndex index( mid.mMeshOrController, sm, meshMaterial); + ColladaMeshIndex index(mid.mMeshOrController, sm, meshMaterial); // if we already have the mesh at the library, just add its index to the node's array - std::map::const_iterator dstMeshIt = mMeshIndexByID.find( index); - if( dstMeshIt != mMeshIndexByID.end()) { - newMeshRefs.push_back( dstMeshIt->second); + std::map::const_iterator dstMeshIt = mMeshIndexByID.find(index); + if (dstMeshIt != mMeshIndexByID.end()) { + newMeshRefs.push_back(dstMeshIt->second); } - else - { + else { // else we have to add the mesh to the collection and store its newly assigned index at the node - aiMesh* dstMesh = CreateMesh( pParser, srcMesh, submesh, srcController, vertexStart, faceStart); + aiMesh* dstMesh = CreateMesh(pParser, srcMesh, submesh, srcController, vertexStart, faceStart); // store the mesh, and store its new index in the node - newMeshRefs.push_back( mMeshes.size()); + newMeshRefs.push_back(mMeshes.size()); mMeshIndexByID[index] = mMeshes.size(); - mMeshes.push_back( dstMesh); + mMeshes.push_back(dstMesh); vertexStart += dstMesh->mNumVertices; faceStart += submesh.mNumFaces; // assign the material index dstMesh->mMaterialIndex = matIdx; - if(dstMesh->mName.length == 0) - { + if (dstMesh->mName.length == 0) { dstMesh->mName = mid.mMeshOrController; } - } + } } } // now place all mesh references we gathered in the target node pTarget->mNumMeshes = static_cast(newMeshRefs.size()); - if( newMeshRefs.size()) - { - struct UIntTypeConverter - { - unsigned int operator()(const size_t& v) const - { + if (newMeshRefs.size()) { + struct UIntTypeConverter { + unsigned int operator()(const size_t& v) const { return static_cast(v); } }; pTarget->mMeshes = new unsigned int[pTarget->mNumMeshes]; - std::transform( newMeshRefs.begin(), newMeshRefs.end(), pTarget->mMeshes, UIntTypeConverter()); + 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) +aiMesh *ColladaLoader::findMesh(const 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) + for (unsigned int i = 0; i < mTargetMeshes.size(); ++i) { + if (std::string(mTargetMeshes[i]->mName.data) == meshid) { return mTargetMeshes[i]; + } + } - return NULL; + return nullptr; } // ------------------------------------------------------------------------------------------------ // 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, - const Collada::Controller* pSrcController, size_t pStartVertex, size_t pStartFace) -{ - aiMesh* dstMesh = new aiMesh; +aiMesh* ColladaLoader::CreateMesh(const ColladaParser& pParser, const Collada::Mesh* pSrcMesh, const Collada::SubMesh& pSubMesh, + const Collada::Controller* pSrcController, size_t pStartVertex, size_t pStartFace) { + std::unique_ptr dstMesh(new aiMesh); dstMesh->mName = pSrcMesh->mName; // 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, size_t(0)); // copy positions dstMesh->mNumVertices = static_cast(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); // normals, if given. HACK: (thom) Due to the glorious Collada spec we never // know if we have the same number of normals as there are positions. So we // also ignore any vertex attribute if it has a different count - if( pSrcMesh->mNormals.size() >= pStartVertex + numVertices) - { + if (pSrcMesh->mNormals.size() >= pStartVertex + numVertices) { dstMesh->mNormals = new aiVector3D[numVertices]; - std::copy( pSrcMesh->mNormals.begin() + pStartVertex, pSrcMesh->mNormals.begin() + + std::copy(pSrcMesh->mNormals.begin() + pStartVertex, pSrcMesh->mNormals.begin() + pStartVertex + numVertices, dstMesh->mNormals); } // tangents, if given. - if( pSrcMesh->mTangents.size() >= pStartVertex + numVertices) - { + if (pSrcMesh->mTangents.size() >= pStartVertex + numVertices) { dstMesh->mTangents = new aiVector3D[numVertices]; - std::copy( pSrcMesh->mTangents.begin() + pStartVertex, pSrcMesh->mTangents.begin() + + std::copy(pSrcMesh->mTangents.begin() + pStartVertex, pSrcMesh->mTangents.begin() + pStartVertex + numVertices, dstMesh->mTangents); } // bitangents, if given. - if( pSrcMesh->mBitangents.size() >= pStartVertex + numVertices) - { + if (pSrcMesh->mBitangents.size() >= pStartVertex + numVertices) { dstMesh->mBitangents = new aiVector3D[numVertices]; - std::copy( pSrcMesh->mBitangents.begin() + pStartVertex, pSrcMesh->mBitangents.begin() + + std::copy(pSrcMesh->mBitangents.begin() + pStartVertex, pSrcMesh->mBitangents.begin() + pStartVertex + numVertices, dstMesh->mBitangents); } // same for texturecoords, as many as we have // empty slots are not allowed, need to pack and adjust UV indexes accordingly - for( size_t a = 0, real = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; a++) - { - if( pSrcMesh->mTexCoords[a].size() >= pStartVertex + numVertices) - { + for (size_t a = 0, real = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) { + if (pSrcMesh->mTexCoords[a].size() >= pStartVertex + numVertices) { dstMesh->mTextureCoords[real] = new aiVector3D[numVertices]; - for( size_t b = 0; b < numVertices; ++b) - dstMesh->mTextureCoords[real][b] = pSrcMesh->mTexCoords[a][pStartVertex+b]; + for (size_t b = 0; b < numVertices; ++b) { + dstMesh->mTextureCoords[real][b] = pSrcMesh->mTexCoords[a][pStartVertex + b]; + } dstMesh->mNumUVComponents[real] = pSrcMesh->mNumUVComponents[a]; ++real; @@ -652,12 +660,10 @@ aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada:: } // same for vertex colors, as many as we have. again the same packing to avoid empty slots - for( size_t a = 0, real = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; a++) - { - if( pSrcMesh->mColors[a].size() >= pStartVertex + numVertices) - { + for (size_t a = 0, real = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a) { + if (pSrcMesh->mColors[a].size() >= pStartVertex + numVertices) { dstMesh->mColors[real] = new aiColor4D[numVertices]; - std::copy( pSrcMesh->mColors[a].begin() + pStartVertex, pSrcMesh->mColors[a].begin() + pStartVertex + numVertices,dstMesh->mColors[real]); + std::copy(pSrcMesh->mColors[a].begin() + pStartVertex, pSrcMesh->mColors[a].begin() + pStartVertex + numVertices, dstMesh->mColors[real]); ++real; } } @@ -666,14 +672,14 @@ aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada:: size_t vertex = 0; dstMesh->mNumFaces = static_cast(pSubMesh.mNumFaces); dstMesh->mFaces = new aiFace[dstMesh->mNumFaces]; - for( size_t a = 0; a < dstMesh->mNumFaces; ++a) - { - size_t s = pSrcMesh->mFaceSize[ pStartFace + a]; + for (size_t a = 0; a < dstMesh->mNumFaces; ++a) { + size_t s = pSrcMesh->mFaceSize[pStartFace + a]; aiFace& face = dstMesh->mFaces[a]; face.mNumIndices = static_cast(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] = static_cast(vertex++); + } } // create morph target meshes if any @@ -681,105 +687,104 @@ aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada:: std::vector targetWeights; Collada::MorphMethod method = Collada::Normalized; - for(std::map::const_iterator it = pParser.mControllerLibrary.begin(); - it != pParser.mControllerLibrary.end(); it++) - { + for (std::map::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); + 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); + 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 "); + 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) - { + 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"); + 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) + 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()) - { + if (targetMeshes.size() > 0 && targetWeights.size() == targetMeshes.size()) { std::vector animMeshes; - for (unsigned int i = 0; i < targetMeshes.size(); i++) - { - aiAnimMesh *animMesh = aiCreateAnimMesh(targetMeshes.at(i)); - animMesh->mWeight = targetWeights[i]; + for (unsigned int i = 0; i < targetMeshes.size(); ++i) { + aiMesh* targetMesh = targetMeshes.at(i); + aiAnimMesh *animMesh = aiCreateAnimMesh(targetMesh); + float weight = targetWeights[i]; + animMesh->mWeight = weight == 0 ? 1.0f : weight; + animMesh->mName = targetMesh->mName; animMeshes.push_back(animMesh); } dstMesh->mMethod = (method == Collada::Relative) - ? aiMorphingMethod_MORPH_RELATIVE - : aiMorphingMethod_MORPH_NORMALIZED; + ? aiMorphingMethod_MORPH_RELATIVE + : aiMorphingMethod_MORPH_NORMALIZED; dstMesh->mAnimMeshes = new aiAnimMesh*[animMeshes.size()]; dstMesh->mNumAnimMeshes = static_cast(animMeshes.size()); - for (unsigned int i = 0; i < animMeshes.size(); i++) + for (unsigned int i = 0; i < animMeshes.size(); ++i) { dstMesh->mAnimMeshes[i] = animMeshes.at(i); + } } // create bones if given - if( pSrcController && pSrcController->mType == Collada::Skin) - { + if (pSrcController && pSrcController->mType == Collada::Skin) { // resolve references - joint names - const Collada::Accessor& jointNamesAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mJointNameSource); - const Collada::Data& jointNames = pParser.ResolveLibraryReference( pParser.mDataLibrary, jointNamesAcc.mSource); + const Collada::Accessor& jointNamesAcc = pParser.ResolveLibraryReference(pParser.mAccessorLibrary, pSrcController->mJointNameSource); + const Collada::Data& jointNames = pParser.ResolveLibraryReference(pParser.mDataLibrary, jointNamesAcc.mSource); // joint offset matrices - const Collada::Accessor& jointMatrixAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mJointOffsetMatrixSource); - const Collada::Data& jointMatrices = pParser.ResolveLibraryReference( pParser.mDataLibrary, jointMatrixAcc.mSource); + const Collada::Accessor& jointMatrixAcc = pParser.ResolveLibraryReference(pParser.mAccessorLibrary, pSrcController->mJointOffsetMatrixSource); + const Collada::Data& jointMatrices = pParser.ResolveLibraryReference(pParser.mDataLibrary, jointMatrixAcc.mSource); // joint vertex_weight name list - should refer to the same list as the joint names above. If not, report and reconsider - const Collada::Accessor& weightNamesAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mWeightInputJoints.mAccessor); - if( &weightNamesAcc != &jointNamesAcc) - throw DeadlyImportError( "Temporary implementational laziness. If you read this, please report to the author."); + const Collada::Accessor& weightNamesAcc = pParser.ResolveLibraryReference(pParser.mAccessorLibrary, pSrcController->mWeightInputJoints.mAccessor); + if (&weightNamesAcc != &jointNamesAcc) + throw DeadlyImportError("Temporary implementational laziness. If you read this, please report to the author."); // vertex weights - const Collada::Accessor& weightsAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mWeightInputWeights.mAccessor); - const Collada::Data& weights = pParser.ResolveLibraryReference( pParser.mDataLibrary, weightsAcc.mSource); + const Collada::Accessor& weightsAcc = pParser.ResolveLibraryReference(pParser.mAccessorLibrary, pSrcController->mWeightInputWeights.mAccessor); + const Collada::Data& weights = pParser.ResolveLibraryReference(pParser.mDataLibrary, weightsAcc.mSource); - if( !jointNames.mIsStringArray || jointMatrices.mIsStringArray || weights.mIsStringArray) - throw DeadlyImportError( "Data type mismatch while resolving mesh joints"); + if (!jointNames.mIsStringArray || jointMatrices.mIsStringArray || weights.mIsStringArray) + throw DeadlyImportError("Data type mismatch while resolving mesh joints"); // sanity check: we rely on the vertex weights always coming as pairs of BoneIndex-WeightIndex - if( pSrcController->mWeightInputJoints.mOffset != 0 || pSrcController->mWeightInputWeights.mOffset != 1) - throw DeadlyImportError( "Unsupported vertex_weight addressing scheme. "); + if (pSrcController->mWeightInputJoints.mOffset != 0 || pSrcController->mWeightInputWeights.mOffset != 1) + throw DeadlyImportError("Unsupported vertex_weight addressing scheme. "); // create containers to collect the weights for each bone size_t numBones = jointNames.mStrings.size(); - std::vector > dstBones( numBones); + std::vector > dstBones(numBones); // build a temporary array of pointers to the start of each vertex's weights typedef std::vector< std::pair > IndexPairVector; std::vector weightStartPerVertex; - weightStartPerVertex.resize(pSrcController->mWeightCounts.size(),pSrcController->mWeights.end()); + weightStartPerVertex.resize(pSrcController->mWeightCounts.size(), pSrcController->mWeights.end()); IndexPairVector::const_iterator pit = pSrcController->mWeights.begin(); - for( size_t a = 0; a < pSrcController->mWeightCounts.size(); ++a) - { + for (size_t a = 0; a < pSrcController->mWeightCounts.size(); ++a) { weightStartPerVertex[a] = pit; pit += pSrcController->mWeightCounts[a]; } // now for each vertex put the corresponding vertex weights into each bone's weight collection - for( size_t a = pStartVertex; a < pStartVertex + numVertices; ++a) - { + for (size_t a = pStartVertex; a < pStartVertex + numVertices; ++a) { // which position index was responsible for this vertex? that's also the index by which // the controller assigns the vertex weights size_t orgIndex = pSrcMesh->mFacePosIndices[a]; @@ -787,58 +792,62 @@ aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada:: IndexPairVector::const_iterator iit = weightStartPerVertex[orgIndex]; size_t pairCount = pSrcController->mWeightCounts[orgIndex]; - for( size_t b = 0; b < pairCount; ++b, ++iit) - { - size_t jointIndex = iit->first; - size_t vertexIndex = iit->second; - ai_real weight = ReadFloat( weightsAcc, weights, vertexIndex, 0); + for( size_t b = 0; b < pairCount; ++b, ++iit) { + const size_t jointIndex = iit->first; + const size_t vertexIndex = iit->second; + ai_real weight = 1.0f; + if (!weights.mValues.empty()) { + weight = ReadFloat(weightsAcc, weights, vertexIndex, 0); + } // one day I gonna kill that XSI Collada exporter - if( weight > 0.0f) + if (weight > 0.0f) { aiVertexWeight w; w.mVertexId = static_cast(a - pStartVertex); w.mWeight = weight; - dstBones[jointIndex].push_back( w); + dstBones[jointIndex].push_back(w); } } } // count the number of bones which influence vertices of the current submesh size_t numRemainingBones = 0; - for( std::vector >::const_iterator it = dstBones.begin(); it != dstBones.end(); ++it) - if( it->size() > 0) - numRemainingBones++; + for( std::vector >::const_iterator it = dstBones.begin(); it != dstBones.end(); ++it) { + if( it->size() > 0) { + ++numRemainingBones; + } + } // create bone array and copy bone weights one by one dstMesh->mNumBones = static_cast(numRemainingBones); dstMesh->mBones = new aiBone*[numRemainingBones]; size_t boneCount = 0; - for( size_t a = 0; a < numBones; ++a) - { + for( size_t a = 0; a < numBones; ++a) { // omit bones without weights - if( dstBones[a].size() == 0) + if( dstBones[a].empty() ) { continue; + } // create bone with its weights aiBone* bone = new aiBone; - bone->mName = ReadString( jointNamesAcc, jointNames, a); - bone->mOffsetMatrix.a1 = ReadFloat( jointMatrixAcc, jointMatrices, a, 0); - bone->mOffsetMatrix.a2 = ReadFloat( jointMatrixAcc, jointMatrices, a, 1); - bone->mOffsetMatrix.a3 = ReadFloat( jointMatrixAcc, jointMatrices, a, 2); - bone->mOffsetMatrix.a4 = ReadFloat( jointMatrixAcc, jointMatrices, a, 3); - bone->mOffsetMatrix.b1 = ReadFloat( jointMatrixAcc, jointMatrices, a, 4); - bone->mOffsetMatrix.b2 = ReadFloat( jointMatrixAcc, jointMatrices, a, 5); - bone->mOffsetMatrix.b3 = ReadFloat( jointMatrixAcc, jointMatrices, a, 6); - bone->mOffsetMatrix.b4 = ReadFloat( jointMatrixAcc, jointMatrices, a, 7); - bone->mOffsetMatrix.c1 = ReadFloat( jointMatrixAcc, jointMatrices, a, 8); - bone->mOffsetMatrix.c2 = ReadFloat( jointMatrixAcc, jointMatrices, a, 9); - bone->mOffsetMatrix.c3 = ReadFloat( jointMatrixAcc, jointMatrices, a, 10); - bone->mOffsetMatrix.c4 = ReadFloat( jointMatrixAcc, jointMatrices, a, 11); + bone->mName = ReadString(jointNamesAcc, jointNames, a); + bone->mOffsetMatrix.a1 = ReadFloat(jointMatrixAcc, jointMatrices, a, 0); + bone->mOffsetMatrix.a2 = ReadFloat(jointMatrixAcc, jointMatrices, a, 1); + bone->mOffsetMatrix.a3 = ReadFloat(jointMatrixAcc, jointMatrices, a, 2); + bone->mOffsetMatrix.a4 = ReadFloat(jointMatrixAcc, jointMatrices, a, 3); + bone->mOffsetMatrix.b1 = ReadFloat(jointMatrixAcc, jointMatrices, a, 4); + bone->mOffsetMatrix.b2 = ReadFloat(jointMatrixAcc, jointMatrices, a, 5); + bone->mOffsetMatrix.b3 = ReadFloat(jointMatrixAcc, jointMatrices, a, 6); + bone->mOffsetMatrix.b4 = ReadFloat(jointMatrixAcc, jointMatrices, a, 7); + bone->mOffsetMatrix.c1 = ReadFloat(jointMatrixAcc, jointMatrices, a, 8); + bone->mOffsetMatrix.c2 = ReadFloat(jointMatrixAcc, jointMatrices, a, 9); + bone->mOffsetMatrix.c3 = ReadFloat(jointMatrixAcc, jointMatrices, a, 10); + bone->mOffsetMatrix.c4 = ReadFloat(jointMatrixAcc, jointMatrices, a, 11); bone->mNumWeights = static_cast(dstBones[a].size()); 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); // apply bind shape matrix to offset matrix aiMatrix4x4 bindShapeMatrix; @@ -865,119 +874,112 @@ aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada:: // and replace the bone's name by the node's name so that the user can use the standard // find-by-name method to associate nodes with bones. const Collada::Node* bnode = FindNode( pParser.mRootNode, bone->mName.data); - if( !bnode) + if( !bnode) { bnode = FindNodeBySID( pParser.mRootNode, bone->mName.data); + } // assign the name that we would have assigned for the source node - if( bnode) + if( bnode) { bone->mName.Set( FindNameForNode( bnode)); - else + } else { ASSIMP_LOG_WARN_F( "ColladaLoader::CreateMesh(): could not find corresponding node for joint \"", bone->mName.data, "\"." ); + } // and insert bone dstMesh->mBones[boneCount++] = bone; } } - return dstMesh; + return dstMesh.release(); } // ------------------------------------------------------------------------------------------------ // Stores all meshes in the given scene -void ColladaLoader::StoreSceneMeshes( aiScene* pScene) -{ +void ColladaLoader::StoreSceneMeshes( aiScene* pScene) { pScene->mNumMeshes = static_cast(mMeshes.size()); - if( mMeshes.size() > 0) - { - pScene->mMeshes = new aiMesh*[mMeshes.size()]; - std::copy( mMeshes.begin(), mMeshes.end(), pScene->mMeshes); - mMeshes.clear(); + if( mMeshes.empty() ) { + return; } + pScene->mMeshes = new aiMesh*[mMeshes.size()]; + std::copy( mMeshes.begin(), mMeshes.end(), pScene->mMeshes); + mMeshes.clear(); } // ------------------------------------------------------------------------------------------------ // Stores all cameras in the given scene -void ColladaLoader::StoreSceneCameras( aiScene* pScene) -{ +void ColladaLoader::StoreSceneCameras( aiScene* pScene) { pScene->mNumCameras = static_cast(mCameras.size()); - if( mCameras.size() > 0) - { - pScene->mCameras = new aiCamera*[mCameras.size()]; - std::copy( mCameras.begin(), mCameras.end(), pScene->mCameras); - mCameras.clear(); + if( mCameras.empty() ) { + return; } + pScene->mCameras = new aiCamera*[mCameras.size()]; + std::copy( mCameras.begin(), mCameras.end(), pScene->mCameras); + mCameras.clear(); } // ------------------------------------------------------------------------------------------------ // Stores all lights in the given scene -void ColladaLoader::StoreSceneLights( aiScene* pScene) -{ +void ColladaLoader::StoreSceneLights( aiScene* pScene) { pScene->mNumLights = static_cast(mLights.size()); - if( mLights.size() > 0) - { - pScene->mLights = new aiLight*[mLights.size()]; - std::copy( mLights.begin(), mLights.end(), pScene->mLights); - mLights.clear(); + if( mLights.empty() ) { + return; } + pScene->mLights = new aiLight*[mLights.size()]; + std::copy( mLights.begin(), mLights.end(), pScene->mLights); + mLights.clear(); } // ------------------------------------------------------------------------------------------------ // Stores all textures in the given scene -void ColladaLoader::StoreSceneTextures( aiScene* pScene) -{ +void ColladaLoader::StoreSceneTextures( aiScene* pScene) { pScene->mNumTextures = static_cast(mTextures.size()); - if( mTextures.size() > 0) - { - pScene->mTextures = new aiTexture*[mTextures.size()]; - std::copy( mTextures.begin(), mTextures.end(), pScene->mTextures); - mTextures.clear(); + if( mTextures.empty() ) { + return; } + pScene->mTextures = new aiTexture*[mTextures.size()]; + std::copy( mTextures.begin(), mTextures.end(), pScene->mTextures); + mTextures.clear(); } // ------------------------------------------------------------------------------------------------ // Stores all materials in the given scene -void ColladaLoader::StoreSceneMaterials( aiScene* pScene) -{ +void ColladaLoader::StoreSceneMaterials( aiScene* pScene) { pScene->mNumMaterials = static_cast(newMats.size()); - - if (newMats.size() > 0) { - pScene->mMaterials = new aiMaterial*[newMats.size()]; - for (unsigned int i = 0; i < newMats.size();++i) - pScene->mMaterials[i] = newMats[i].second; - - newMats.clear(); + if (newMats.empty() ) { + return; } + pScene->mMaterials = new aiMaterial*[newMats.size()]; + for (unsigned int i = 0; i < newMats.size();++i) { + pScene->mMaterials[i] = newMats[i].second; + } + newMats.clear(); } // ------------------------------------------------------------------------------------------------ // Stores all animations -void ColladaLoader::StoreAnimations( aiScene* pScene, const ColladaParser& pParser) -{ +void ColladaLoader::StoreAnimations( aiScene* pScene, const ColladaParser& pParser) { // recursively collect all animations from the collada scene - StoreAnimations( pScene, pParser, &pParser.mAnims, ""); + StoreAnimations(pScene, pParser, &pParser.mAnims, ""); // catch special case: many animations with the same length, each affecting only a single node. // we need to unite all those single-node-anims to a proper combined animation - for( size_t a = 0; a < mAnims.size(); ++a) - { + for( size_t a = 0; a < mAnims.size(); ++a) { aiAnimation* templateAnim = mAnims[a]; - if( templateAnim->mNumChannels == 1) - { + if( templateAnim->mNumChannels == 1) { // search for other single-channel-anims with the same duration std::vector collectedAnimIndices; - for( size_t b = a+1; b < mAnims.size(); ++b) - { + for( size_t b = a+1; b < mAnims.size(); ++b) { aiAnimation* other = mAnims[b]; - if( other->mNumChannels == 1 && other->mDuration == templateAnim->mDuration && - other->mTicksPerSecond == templateAnim->mTicksPerSecond ) - collectedAnimIndices.push_back( b); + if (other->mNumChannels == 1 && other->mDuration == templateAnim->mDuration && + other->mTicksPerSecond == templateAnim->mTicksPerSecond) + collectedAnimIndices.push_back(b); } // if there are other animations which fit the template anim, combine all channels into a single anim - if( !collectedAnimIndices.empty() ) + if (!collectedAnimIndices.empty()) { aiAnimation* combinedAnim = new aiAnimation(); - combinedAnim->mName = aiString( std::string( "combinedAnim_") + char( '0' + a)); + combinedAnim->mName = aiString(std::string("combinedAnim_") + char('0' + a)); combinedAnim->mDuration = templateAnim->mDuration; combinedAnim->mTicksPerSecond = templateAnim->mTicksPerSecond; combinedAnim->mNumChannels = static_cast(collectedAnimIndices.size() + 1); @@ -990,7 +992,7 @@ void ColladaLoader::StoreAnimations( aiScene* pScene, const ColladaParser& pPars mAnims[a] = combinedAnim; // move the memory of all other anims to the combined anim and erase them from the source anims - for( size_t b = 0; b < collectedAnimIndices.size(); ++b) + for (size_t b = 0; b < collectedAnimIndices.size(); ++b) { aiAnimation* srcAnimation = mAnims[collectedAnimIndices[b]]; combinedAnim->mChannels[1 + b] = srcAnimation->mChannels[0]; @@ -1000,9 +1002,9 @@ void ColladaLoader::StoreAnimations( aiScene* pScene, const ColladaParser& pPars // in a second go, delete all the single-channel-anims that we've stripped from their channels // back to front to preserve indices - you know, removing an element from a vector moves all elements behind the removed one - while( !collectedAnimIndices.empty() ) + while (!collectedAnimIndices.empty()) { - mAnims.erase( mAnims.begin() + collectedAnimIndices.back()); + mAnims.erase(mAnims.begin() + collectedAnimIndices.back()); collectedAnimIndices.pop_back(); } } @@ -1010,11 +1012,11 @@ void ColladaLoader::StoreAnimations( aiScene* pScene, const ColladaParser& pPars } // now store all anims in the scene - if( !mAnims.empty()) + if (!mAnims.empty()) { pScene->mNumAnimations = static_cast(mAnims.size()); pScene->mAnimations = new aiAnimation*[mAnims.size()]; - std::copy( mAnims.begin(), mAnims.end(), pScene->mAnimations); + std::copy(mAnims.begin(), mAnims.end(), pScene->mAnimations); } mAnims.clear(); @@ -1022,17 +1024,17 @@ void ColladaLoader::StoreAnimations( aiScene* pScene, const ColladaParser& pPars // ------------------------------------------------------------------------------------------------ // Constructs the animations for the given source anim -void ColladaLoader::StoreAnimations( aiScene* pScene, const ColladaParser& pParser, const Collada::Animation* pSrcAnim, const std::string &pPrefix) +void ColladaLoader::StoreAnimations(aiScene* pScene, const ColladaParser& pParser, const Collada::Animation* pSrcAnim, const std::string &pPrefix) { std::string animName = pPrefix.empty() ? pSrcAnim->mName : pPrefix + "_" + pSrcAnim->mName; // create nested animations, if given - for( std::vector::const_iterator it = pSrcAnim->mSubAnims.begin(); it != pSrcAnim->mSubAnims.end(); ++it) - StoreAnimations( pScene, pParser, *it, animName); + for (std::vector::const_iterator it = pSrcAnim->mSubAnims.begin(); it != pSrcAnim->mSubAnims.end(); ++it) + StoreAnimations(pScene, pParser, *it, animName); // create animation channels, if any - if( !pSrcAnim->mChannels.empty()) - CreateAnimation( pScene, pParser, pSrcAnim, animName); + if (!pSrcAnim->mChannels.empty()) + CreateAnimation(pScene, pParser, pSrcAnim, animName); } struct MorphTimeValues @@ -1073,7 +1075,8 @@ void insertMorphTimeValue(std::vector &values, float time, floa { values[i].mKeys.push_back(k); return; - } else if (time > values[i].mTime && time < values[i+1].mTime) + } + else if (time > values[i].mTime && time < values[i + 1].mTime) { MorphTimeValues val; val.mTime = time; @@ -1099,30 +1102,30 @@ float getWeightAtKey(const std::vector &values, int key, unsign // ------------------------------------------------------------------------------------------------ // 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) { // collect a list of animatable nodes std::vector nodes; - CollectNodes( pScene->mRootNode, nodes); + CollectNodes(pScene->mRootNode, nodes); std::vector anims; std::vector morphAnims; - for( std::vector::const_iterator nit = nodes.begin(); nit != nodes.end(); ++nit) + for (std::vector::const_iterator nit = nodes.begin(); nit != nodes.end(); ++nit) { // find all the collada anim channels which refer to the current node std::vector entries; std::string nodeName = (*nit)->mName.data; // find the collada node corresponding to the aiNode - const Collada::Node* srcNode = FindNode( pParser.mRootNode, nodeName); -// ai_assert( srcNode != NULL); - if( !srcNode) + const Collada::Node* srcNode = FindNode(pParser.mRootNode, nodeName); + // ai_assert( srcNode != NULL); + if (!srcNode) continue; // now check all channels if they affect the current node std::string targetID, subElement; - for( std::vector::const_iterator cit = pSrcAnim->mChannels.begin(); + for (std::vector::const_iterator cit = pSrcAnim->mChannels.begin(); cit != pSrcAnim->mChannels.end(); ++cit) { const Collada::AnimationChannel& srcChannel = *cit; @@ -1130,8 +1133,8 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars // we expect the animation target to be of type "nodeName/transformID.subElement". Ignore all others // find the slash that separates the node name - there should be only one - std::string::size_type slashPos = srcChannel.mTarget.find( '/'); - if( slashPos == std::string::npos) + std::string::size_type slashPos = srcChannel.mTarget.find('/'); + if (slashPos == std::string::npos) { std::string::size_type targetPos = srcChannel.mTarget.find(srcNode->mID); if (targetPos == std::string::npos) @@ -1140,44 +1143,45 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars // 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()); + srcChannel.mTarget.length() - targetPos - pSrcAnim->mName.length()); if (entry.mTargetId.front() == '-') entry.mTargetId = entry.mTargetId.substr(1); entries.push_back(entry); continue; } - if( srcChannel.mTarget.find( '/', slashPos+1) != std::string::npos) + if (srcChannel.mTarget.find('/', slashPos + 1) != std::string::npos) continue; targetID.clear(); - targetID = srcChannel.mTarget.substr( 0, slashPos); - if( targetID != srcNode->mID) + targetID = srcChannel.mTarget.substr(0, slashPos); + if (targetID != srcNode->mID) continue; // find the dot that separates the transformID - there should be only one or zero - std::string::size_type dotPos = srcChannel.mTarget.find( '.'); - if( dotPos != std::string::npos) + std::string::size_type dotPos = srcChannel.mTarget.find('.'); + if (dotPos != std::string::npos) { - if( srcChannel.mTarget.find( '.', dotPos+1) != std::string::npos) + if (srcChannel.mTarget.find('.', dotPos + 1) != std::string::npos) continue; - entry.mTransformId = srcChannel.mTarget.substr( slashPos+1, dotPos - slashPos - 1); + entry.mTransformId = srcChannel.mTarget.substr(slashPos + 1, dotPos - slashPos - 1); subElement.clear(); - subElement = srcChannel.mTarget.substr( dotPos+1); - if( subElement == "ANGLE") + subElement = srcChannel.mTarget.substr(dotPos + 1); + if (subElement == "ANGLE") entry.mSubElement = 3; // last number in an Axis-Angle-Transform is the angle - else if( subElement == "X") + else if (subElement == "X") entry.mSubElement = 0; - else if( subElement == "Y") + else if (subElement == "Y") entry.mSubElement = 1; - else if( subElement == "Z") + else if (subElement == "Z") entry.mSubElement = 2; else - ASSIMP_LOG_WARN_F( "Unknown anim subelement <", subElement, ">. Ignoring" ); - } else { + ASSIMP_LOG_WARN_F("Unknown anim subelement <", subElement, ">. Ignoring"); + } + else { // no subelement following, transformId is remaining string - entry.mTransformId = srcChannel.mTarget.substr( slashPos+1); + entry.mTransformId = srcChannel.mTarget.substr(slashPos + 1); } std::string::size_type bracketPos = srcChannel.mTarget.find('('); @@ -1223,194 +1227,196 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars // determine which transform step is affected by this channel entry.mTransformIndex = SIZE_MAX; - for( size_t a = 0; a < srcNode->mTransforms.size(); ++a) - if( srcNode->mTransforms[a].mID == entry.mTransformId) + for (size_t a = 0; a < srcNode->mTransforms.size(); ++a) + if (srcNode->mTransforms[a].mID == entry.mTransformId) entry.mTransformIndex = a; - if( entry.mTransformIndex == SIZE_MAX) + if (entry.mTransformIndex == SIZE_MAX) { if (entry.mTransformId.find("morph-weights") != std::string::npos) { entry.mTargetId = entry.mTransformId; entry.mTransformId = ""; - } else + } + else continue; } entry.mChannel = &(*cit); - entries.push_back( entry); + entries.push_back(entry); } // if there's no channel affecting the current node, we skip it - if( entries.empty()) + if (entries.empty()) continue; // resolve the data pointers for all anim channels. Find the minimum time while we're at it - ai_real startTime = ai_real( 1e20 ), endTime = ai_real( -1e20 ); - for( std::vector::iterator it = entries.begin(); it != entries.end(); ++it) + ai_real startTime = ai_real(1e20), endTime = ai_real(-1e20); + for (std::vector::iterator it = entries.begin(); it != entries.end(); ++it) { Collada::ChannelEntry& e = *it; - e.mTimeAccessor = &pParser.ResolveLibraryReference( pParser.mAccessorLibrary, e.mChannel->mSourceTimes); - e.mTimeData = &pParser.ResolveLibraryReference( pParser.mDataLibrary, e.mTimeAccessor->mSource); - e.mValueAccessor = &pParser.ResolveLibraryReference( pParser.mAccessorLibrary, e.mChannel->mSourceValues); - e.mValueData = &pParser.ResolveLibraryReference( pParser.mDataLibrary, e.mValueAccessor->mSource); + e.mTimeAccessor = &pParser.ResolveLibraryReference(pParser.mAccessorLibrary, e.mChannel->mSourceTimes); + e.mTimeData = &pParser.ResolveLibraryReference(pParser.mDataLibrary, e.mTimeAccessor->mSource); + e.mValueAccessor = &pParser.ResolveLibraryReference(pParser.mAccessorLibrary, e.mChannel->mSourceValues); + e.mValueData = &pParser.ResolveLibraryReference(pParser.mDataLibrary, e.mValueAccessor->mSource); // time count and value count must match - if( e.mTimeAccessor->mCount != e.mValueAccessor->mCount) - throw DeadlyImportError( format() << "Time count / value count mismatch in animation channel \"" << e.mChannel->mTarget << "\"." ); + if (e.mTimeAccessor->mCount != e.mValueAccessor->mCount) + throw DeadlyImportError(format() << "Time count / value count mismatch in animation channel \"" << e.mChannel->mTarget << "\"."); - if( e.mTimeAccessor->mCount > 0 ) - { - // find bounding times - startTime = std::min( startTime, ReadFloat( *e.mTimeAccessor, *e.mTimeData, 0, 0)); - endTime = std::max( endTime, ReadFloat( *e.mTimeAccessor, *e.mTimeData, e.mTimeAccessor->mCount-1, 0)); - } + if (e.mTimeAccessor->mCount > 0) + { + // find bounding times + startTime = std::min(startTime, ReadFloat(*e.mTimeAccessor, *e.mTimeData, 0, 0)); + endTime = std::max(endTime, ReadFloat(*e.mTimeAccessor, *e.mTimeData, e.mTimeAccessor->mCount - 1, 0)); + } } - std::vector resultTrafos; - if( !entries.empty() && entries.front().mTimeAccessor->mCount > 0 ) - { - // create a local transformation chain of the node's transforms - std::vector transforms = srcNode->mTransforms; + std::vector resultTrafos; + if (!entries.empty() && entries.front().mTimeAccessor->mCount > 0) + { + // create a local transformation chain of the node's transforms + std::vector transforms = srcNode->mTransforms; - // now for every unique point in time, find or interpolate the key values for that time - // and apply them to the transform chain. Then the node's present transformation can be calculated. - ai_real time = startTime; - while( 1) - { - for( std::vector::iterator it = entries.begin(); it != entries.end(); ++it) - { - Collada::ChannelEntry& e = *it; + // now for every unique point in time, find or interpolate the key values for that time + // and apply them to the transform chain. Then the node's present transformation can be calculated. + ai_real time = startTime; + while (1) + { + for (std::vector::iterator it = entries.begin(); it != entries.end(); ++it) + { + Collada::ChannelEntry& e = *it; - // find the keyframe behind the current point in time - size_t pos = 0; - ai_real postTime = 0.0; - while( 1) - { - if( pos >= e.mTimeAccessor->mCount) - break; - postTime = ReadFloat( *e.mTimeAccessor, *e.mTimeData, pos, 0); - if( postTime >= time) - break; - ++pos; - } + // find the keyframe behind the current point in time + size_t pos = 0; + ai_real postTime = 0.0; + while (1) + { + if (pos >= e.mTimeAccessor->mCount) + break; + postTime = ReadFloat(*e.mTimeAccessor, *e.mTimeData, pos, 0); + if (postTime >= time) + break; + ++pos; + } - pos = std::min( pos, e.mTimeAccessor->mCount-1); + pos = std::min(pos, e.mTimeAccessor->mCount - 1); - // read values from there - ai_real temp[16]; - for( size_t c = 0; c < e.mValueAccessor->mSize; ++c) - temp[c] = ReadFloat( *e.mValueAccessor, *e.mValueData, pos, c); + // read values from there + ai_real temp[16]; + for (size_t c = 0; c < e.mValueAccessor->mSize; ++c) + temp[c] = ReadFloat(*e.mValueAccessor, *e.mValueData, pos, c); - // if not exactly at the key time, interpolate with previous value set - if( postTime > time && pos > 0) - { - ai_real preTime = ReadFloat( *e.mTimeAccessor, *e.mTimeData, pos-1, 0); - ai_real factor = (time - postTime) / (preTime - postTime); + // if not exactly at the key time, interpolate with previous value set + if (postTime > time && pos > 0) + { + ai_real preTime = ReadFloat(*e.mTimeAccessor, *e.mTimeData, pos - 1, 0); + ai_real factor = (time - postTime) / (preTime - postTime); - for( size_t c = 0; c < e.mValueAccessor->mSize; ++c) - { - ai_real v = ReadFloat( *e.mValueAccessor, *e.mValueData, pos-1, c); - temp[c] += (v - temp[c]) * factor; - } - } + for (size_t c = 0; c < e.mValueAccessor->mSize; ++c) + { + ai_real v = ReadFloat(*e.mValueAccessor, *e.mValueData, pos - 1, c); + temp[c] += (v - temp[c]) * factor; + } + } - // Apply values to current transformation - std::copy( temp, temp + e.mValueAccessor->mSize, transforms[e.mTransformIndex].f + e.mSubElement); - } + // Apply values to current transformation + std::copy(temp, temp + e.mValueAccessor->mSize, transforms[e.mTransformIndex].f + e.mSubElement); + } - // Calculate resulting transformation - aiMatrix4x4 mat = pParser.CalculateResultTransform( transforms); + // Calculate resulting transformation + aiMatrix4x4 mat = pParser.CalculateResultTransform(transforms); - // out of laziness: we store the time in matrix.d4 - mat.d4 = time; - resultTrafos.push_back( mat); + // out of laziness: we store the time in matrix.d4 + mat.d4 = time; + resultTrafos.push_back(mat); - // find next point in time to evaluate. That's the closest frame larger than the current in any channel - ai_real nextTime = ai_real( 1e20 ); - for( std::vector::iterator it = entries.begin(); it != entries.end(); ++it) - { - Collada::ChannelEntry& channelElement = *it; + // find next point in time to evaluate. That's the closest frame larger than the current in any channel + ai_real nextTime = ai_real(1e20); + for (std::vector::iterator it = entries.begin(); it != entries.end(); ++it) + { + Collada::ChannelEntry& channelElement = *it; - // find the next time value larger than the current - size_t pos = 0; - while( pos < channelElement.mTimeAccessor->mCount) - { - const ai_real t = ReadFloat( *channelElement.mTimeAccessor, *channelElement.mTimeData, pos, 0); - if( t > time) - { - nextTime = std::min( nextTime, t); - break; - } - ++pos; - } + // find the next time value larger than the current + size_t pos = 0; + while (pos < channelElement.mTimeAccessor->mCount) + { + const ai_real t = ReadFloat(*channelElement.mTimeAccessor, *channelElement.mTimeData, pos, 0); + if (t > time) + { + nextTime = std::min(nextTime, t); + break; + } + ++pos; + } - // https://github.com/assimp/assimp/issues/458 - // Sub-sample axis-angle channels if the delta between two consecutive - // key-frame angles is >= 180 degrees. - if (transforms[channelElement.mTransformIndex].mType == Collada::TF_ROTATE && channelElement.mSubElement == 3 && pos > 0 && pos < channelElement.mTimeAccessor->mCount) { - const ai_real cur_key_angle = ReadFloat(*channelElement.mValueAccessor, *channelElement.mValueData, pos, 0); - const ai_real last_key_angle = ReadFloat(*channelElement.mValueAccessor, *channelElement.mValueData, pos - 1, 0); - const ai_real cur_key_time = ReadFloat(*channelElement.mTimeAccessor, *channelElement.mTimeData, pos, 0); - const ai_real last_key_time = ReadFloat(*channelElement.mTimeAccessor, *channelElement.mTimeData, pos - 1, 0); - 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); - if (delta >= 180.0) { - const int subSampleCount = static_cast(std::floor(delta / 90.0)); - if (cur_key_time != time) { - const ai_real nextSampleTime = time + (cur_key_time - time) / subSampleCount; - nextTime = std::min(nextTime, nextSampleTime); - } - } - } - } + // https://github.com/assimp/assimp/issues/458 + // Sub-sample axis-angle channels if the delta between two consecutive + // key-frame angles is >= 180 degrees. + if (transforms[channelElement.mTransformIndex].mType == Collada::TF_ROTATE && channelElement.mSubElement == 3 && pos > 0 && pos < channelElement.mTimeAccessor->mCount) { + const ai_real cur_key_angle = ReadFloat(*channelElement.mValueAccessor, *channelElement.mValueData, pos, 0); + const ai_real last_key_angle = ReadFloat(*channelElement.mValueAccessor, *channelElement.mValueData, pos - 1, 0); + const ai_real cur_key_time = ReadFloat(*channelElement.mTimeAccessor, *channelElement.mTimeData, pos, 0); + const ai_real last_key_time = ReadFloat(*channelElement.mTimeAccessor, *channelElement.mTimeData, pos - 1, 0); + 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); + if (delta >= 180.0) { + const int subSampleCount = static_cast(std::floor(delta / 90.0)); + if (cur_key_time != time) { + const ai_real nextSampleTime = time + (cur_key_time - time) / subSampleCount; + nextTime = std::min(nextTime, nextSampleTime); + } + } + } + } - // no more keys on any channel after the current time -> we're done - if( nextTime > 1e19) - break; + // no more keys on any channel after the current time -> we're done + if (nextTime > 1e19) + break; - // else construct next keyframe at this following time point - time = nextTime; - } - } + // else construct next keyframe at this following time point + time = nextTime; + } + } // there should be some keyframes, but we aren't that fixated on valid input data // ai_assert( resultTrafos.size() > 0); // build an animation channel for the given node out of these trafo keys - if( !resultTrafos.empty() ) + if (!resultTrafos.empty()) { - aiNodeAnim* dstAnim = new aiNodeAnim; - dstAnim->mNodeName = nodeName; - dstAnim->mNumPositionKeys = static_cast(resultTrafos.size()); - dstAnim->mNumRotationKeys = static_cast(resultTrafos.size()); - dstAnim->mNumScalingKeys = static_cast(resultTrafos.size()); - dstAnim->mPositionKeys = new aiVectorKey[resultTrafos.size()]; - dstAnim->mRotationKeys = new aiQuatKey[resultTrafos.size()]; - dstAnim->mScalingKeys = new aiVectorKey[resultTrafos.size()]; + aiNodeAnim* dstAnim = new aiNodeAnim; + dstAnim->mNodeName = nodeName; + dstAnim->mNumPositionKeys = static_cast(resultTrafos.size()); + dstAnim->mNumRotationKeys = static_cast(resultTrafos.size()); + dstAnim->mNumScalingKeys = static_cast(resultTrafos.size()); + dstAnim->mPositionKeys = new aiVectorKey[resultTrafos.size()]; + dstAnim->mRotationKeys = new aiQuatKey[resultTrafos.size()]; + dstAnim->mScalingKeys = new aiVectorKey[resultTrafos.size()]; - for( size_t a = 0; a < resultTrafos.size(); ++a) - { - aiMatrix4x4 mat = resultTrafos[a]; - double time = double( mat.d4); // remember? time is stored in mat.d4 - mat.d4 = 1.0f; + for (size_t a = 0; a < resultTrafos.size(); ++a) + { + aiMatrix4x4 mat = resultTrafos[a]; + double time = double(mat.d4); // remember? time is stored in mat.d4 + mat.d4 = 1.0f; - dstAnim->mPositionKeys[a].mTime = time; - dstAnim->mRotationKeys[a].mTime = time; - dstAnim->mScalingKeys[a].mTime = time; - mat.Decompose( dstAnim->mScalingKeys[a].mValue, dstAnim->mRotationKeys[a].mValue, dstAnim->mPositionKeys[a].mValue); - } + dstAnim->mPositionKeys[a].mTime = time; + dstAnim->mRotationKeys[a].mTime = time; + dstAnim->mScalingKeys[a].mTime = time; + mat.Decompose(dstAnim->mScalingKeys[a].mValue, dstAnim->mRotationKeys[a].mValue, dstAnim->mPositionKeys[a].mValue); + } - anims.push_back( dstAnim); - } else + anims.push_back(dstAnim); + } + else { - ASSIMP_LOG_WARN( "Collada loader: found empty animation channel, ignored. Please check your exporter."); + ASSIMP_LOG_WARN("Collada loader: found empty animation channel, ignored. Please check your exporter."); } - if( !entries.empty() && entries.front().mTimeAccessor->mCount > 0 ) + if (!entries.empty() && entries.front().mTimeAccessor->mCount > 0) { std::vector morphChannels; - for( std::vector::iterator it = entries.begin(); it != entries.end(); ++it) + for (std::vector::iterator it = entries.begin(); it != entries.end(); ++it) { Collada::ChannelEntry& e = *it; @@ -1433,7 +1439,7 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars std::vector morphTimeValues; int morphAnimChannelIndex = 0; - for( std::vector::iterator it = morphChannels.begin(); it != morphChannels.end(); ++it) + for (std::vector::iterator it = morphChannels.begin(); it != morphChannels.end(); ++it) { Collada::ChannelEntry& e = *it; std::string::size_type apos = e.mTargetId.find('('); @@ -1455,8 +1461,8 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars for (unsigned int key = 0; key < morphAnim->mNumKeys; key++) { morphAnim->mKeys[key].mNumValuesAndWeights = static_cast(morphChannels.size()); - morphAnim->mKeys[key].mValues = new unsigned int [morphChannels.size()]; - morphAnim->mKeys[key].mWeights = new double [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++) @@ -1471,48 +1477,48 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars } } - if( !anims.empty() || !morphAnims.empty()) + if (!anims.empty() || !morphAnims.empty()) { aiAnimation* anim = new aiAnimation; - anim->mName.Set( pName); + anim->mName.Set(pName); anim->mNumChannels = static_cast(anims.size()); if (anim->mNumChannels > 0) { anim->mChannels = new aiNodeAnim*[anims.size()]; - std::copy( anims.begin(), anims.end(), anim->mChannels); + std::copy(anims.begin(), anims.end(), anim->mChannels); } anim->mNumMorphMeshChannels = static_cast(morphAnims.size()); if (anim->mNumMorphMeshChannels > 0) { anim->mMorphMeshChannels = new aiMeshMorphAnim*[anim->mNumMorphMeshChannels]; - std::copy( morphAnims.begin(), morphAnims.end(), anim->mMorphMeshChannels); + std::copy(morphAnims.begin(), morphAnims.end(), anim->mMorphMeshChannels); } 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]->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]->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]->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->mDuration = std::max(anim->mDuration, morphAnims[a]->mKeys[morphAnims[a]->mNumKeys - 1].mTime); } anim->mTicksPerSecond = 1; - mAnims.push_back( anim); + mAnims.push_back(anim); } } // ------------------------------------------------------------------------------------------------ // Add a texture to a material structure -void ColladaLoader::AddTexture ( aiMaterial& mat, const ColladaParser& pParser, +void ColladaLoader::AddTexture(aiMaterial& mat, const ColladaParser& pParser, const Collada::Effect& effect, const Collada::Sampler& sampler, aiTextureType type, unsigned int idx) { // first of all, basic file name - const aiString name = FindFilenameForEffectTexture( pParser, effect, sampler.mName ); - mat.AddProperty( &name, _AI_MATKEY_TEXTURE_BASE, type, idx ); + const aiString name = FindFilenameForEffectTexture(pParser, effect, sampler.mName); + mat.AddProperty(&name, _AI_MATKEY_TEXTURE_BASE, type, idx); // mapping mode int map = aiTextureMapMode_Clamp; @@ -1521,7 +1527,7 @@ void ColladaLoader::AddTexture ( aiMaterial& mat, const ColladaParser& pParser, if (sampler.mWrapU && sampler.mMirrorU) map = aiTextureMapMode_Mirror; - mat.AddProperty( &map, 1, _AI_MATKEY_MAPPINGMODE_U_BASE, type, idx); + mat.AddProperty(&map, 1, _AI_MATKEY_MAPPINGMODE_U_BASE, type, idx); map = aiTextureMapMode_Clamp; if (sampler.mWrapV) @@ -1529,18 +1535,18 @@ void ColladaLoader::AddTexture ( aiMaterial& mat, const ColladaParser& pParser, if (sampler.mWrapV && sampler.mMirrorV) map = aiTextureMapMode_Mirror; - mat.AddProperty( &map, 1, _AI_MATKEY_MAPPINGMODE_V_BASE, type, idx); + mat.AddProperty(&map, 1, _AI_MATKEY_MAPPINGMODE_V_BASE, type, idx); // UV transformation mat.AddProperty(&sampler.mTransform, 1, _AI_MATKEY_UVTRANSFORM_BASE, type, idx); // Blend mode - mat.AddProperty((int*)&sampler.mOp , 1, + mat.AddProperty((int*)&sampler.mOp, 1, _AI_MATKEY_TEXBLEND_BASE, type, idx); // Blend factor - mat.AddProperty((ai_real*)&sampler.mWeighting , 1, + mat.AddProperty((ai_real*)&sampler.mWeighting, 1, _AI_MATKEY_TEXBLEND_BASE, type, idx); // UV source index ... if we didn't resolve the mapping, it is actually just @@ -1552,7 +1558,7 @@ void ColladaLoader::AddTexture ( aiMaterial& mat, const ColladaParser& pParser, map = sampler.mUVId; else { map = -1; - for (std::string::const_iterator it = sampler.mUVChannel.begin();it != sampler.mUVChannel.end(); ++it){ + for (std::string::const_iterator it = sampler.mUVChannel.begin(); it != sampler.mUVChannel.end(); ++it) { if (IsNumeric(*it)) { map = strtoul10(&(*it)); break; @@ -1563,12 +1569,12 @@ void ColladaLoader::AddTexture ( aiMaterial& mat, const ColladaParser& pParser, map = 0; } } - mat.AddProperty(&map,1,_AI_MATKEY_UVWSRC_BASE,type,idx); + mat.AddProperty(&map, 1, _AI_MATKEY_UVWSRC_BASE, type, idx); } // ------------------------------------------------------------------------------------------------ // Fills materials from the collada material definitions -void ColladaLoader::FillMaterials( const ColladaParser& pParser, aiScene* /*pScene*/) +void ColladaLoader::FillMaterials(const ColladaParser& pParser, aiScene* /*pScene*/) { for (auto &elem : newMats) { @@ -1580,7 +1586,7 @@ void ColladaLoader::FillMaterials( const ColladaParser& pParser, aiScene* /*pSce if (effect.mFaceted) /* fixme */ shadeMode = aiShadingMode_Flat; else { - switch( effect.mShadeType) + switch (effect.mShadeType) { case Collada::Shade_Constant: shadeMode = aiShadingMode_NoShading; @@ -1601,56 +1607,57 @@ void ColladaLoader::FillMaterials( const ColladaParser& pParser, aiScene* /*pSce break; } } - mat.AddProperty( &shadeMode, 1, AI_MATKEY_SHADING_MODEL); + mat.AddProperty(&shadeMode, 1, AI_MATKEY_SHADING_MODEL); // double-sided? shadeMode = effect.mDoubleSided; - mat.AddProperty( &shadeMode, 1, AI_MATKEY_TWOSIDED); + mat.AddProperty(&shadeMode, 1, AI_MATKEY_TWOSIDED); // wireframe? shadeMode = effect.mWireframe; - mat.AddProperty( &shadeMode, 1, AI_MATKEY_ENABLE_WIREFRAME); + mat.AddProperty(&shadeMode, 1, AI_MATKEY_ENABLE_WIREFRAME); // add material colors - mat.AddProperty( &effect.mAmbient, 1,AI_MATKEY_COLOR_AMBIENT); - mat.AddProperty( &effect.mDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE); - mat.AddProperty( &effect.mSpecular, 1,AI_MATKEY_COLOR_SPECULAR); - mat.AddProperty( &effect.mEmissive, 1, AI_MATKEY_COLOR_EMISSIVE); - mat.AddProperty( &effect.mReflective, 1, AI_MATKEY_COLOR_REFLECTIVE); + mat.AddProperty(&effect.mAmbient, 1, AI_MATKEY_COLOR_AMBIENT); + mat.AddProperty(&effect.mDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE); + mat.AddProperty(&effect.mSpecular, 1, AI_MATKEY_COLOR_SPECULAR); + mat.AddProperty(&effect.mEmissive, 1, AI_MATKEY_COLOR_EMISSIVE); + mat.AddProperty(&effect.mReflective, 1, AI_MATKEY_COLOR_REFLECTIVE); // scalar properties - mat.AddProperty( &effect.mShininess, 1, AI_MATKEY_SHININESS); - mat.AddProperty( &effect.mReflectivity, 1, AI_MATKEY_REFLECTIVITY); - mat.AddProperty( &effect.mRefractIndex, 1, AI_MATKEY_REFRACTI); + mat.AddProperty(&effect.mShininess, 1, AI_MATKEY_SHININESS); + mat.AddProperty(&effect.mReflectivity, 1, AI_MATKEY_REFLECTIVITY); + mat.AddProperty(&effect.mRefractIndex, 1, AI_MATKEY_REFRACTI); // transparency, a very hard one. seemingly not all files are following the // specification here (1.0 transparency => completely opaque)... // therefore, we let the opportunity for the user to manually invert // the transparency if necessary and we add preliminary support for RGB_ZERO mode - if(effect.mTransparency >= 0.f && effect.mTransparency <= 1.f) { + if (effect.mTransparency >= 0.f && effect.mTransparency <= 1.f) { // handle RGB transparency completely, cf Collada specs 1.5.0 pages 249 and 304 - if(effect.mRGBTransparency) { - // use luminance as defined by ISO/CIE color standards (see ITU-R Recommendation BT.709-4) + if (effect.mRGBTransparency) { + // use luminance as defined by ISO/CIE color standards (see ITU-R Recommendation BT.709-4) effect.mTransparency *= ( 0.212671f * effect.mTransparent.r + 0.715160f * effect.mTransparent.g + 0.072169f * effect.mTransparent.b - ); + ); effect.mTransparent.a = 1.f; - mat.AddProperty( &effect.mTransparent, 1, AI_MATKEY_COLOR_TRANSPARENT ); - } else { - effect.mTransparency *= effect.mTransparent.a; + mat.AddProperty(&effect.mTransparent, 1, AI_MATKEY_COLOR_TRANSPARENT); + } + else { + effect.mTransparency *= effect.mTransparent.a; } - if(effect.mInvertTransparency) { + if (effect.mInvertTransparency) { effect.mTransparency = 1.f - effect.mTransparency; } // Is the material finally transparent ? if (effect.mHasTransparency || effect.mTransparency < 1.f) { - mat.AddProperty( &effect.mTransparency, 1, AI_MATKEY_OPACITY ); + mat.AddProperty(&effect.mTransparency, 1, AI_MATKEY_OPACITY); } } @@ -1660,87 +1667,87 @@ void ColladaLoader::FillMaterials( const ColladaParser& pParser, aiScene* /*pSce AddTexture(mat, pParser, effect, effect.mTexAmbient, aiTextureType_LIGHTMAP); } - if( !effect.mTexEmissive.mName.empty()) - AddTexture( mat, pParser, effect, effect.mTexEmissive, aiTextureType_EMISSIVE); + if (!effect.mTexEmissive.mName.empty()) + AddTexture(mat, pParser, effect, effect.mTexEmissive, aiTextureType_EMISSIVE); - if( !effect.mTexSpecular.mName.empty()) - AddTexture( mat, pParser, effect, effect.mTexSpecular, aiTextureType_SPECULAR); + if (!effect.mTexSpecular.mName.empty()) + AddTexture(mat, pParser, effect, effect.mTexSpecular, aiTextureType_SPECULAR); - if( !effect.mTexDiffuse.mName.empty()) - AddTexture( mat, pParser, effect, effect.mTexDiffuse, aiTextureType_DIFFUSE); + if (!effect.mTexDiffuse.mName.empty()) + AddTexture(mat, pParser, effect, effect.mTexDiffuse, aiTextureType_DIFFUSE); - if( !effect.mTexBump.mName.empty()) - AddTexture( mat, pParser, effect, effect.mTexBump, aiTextureType_NORMALS); + if (!effect.mTexBump.mName.empty()) + AddTexture(mat, pParser, effect, effect.mTexBump, aiTextureType_NORMALS); - if( !effect.mTexTransparent.mName.empty()) - AddTexture( mat, pParser, effect, effect.mTexTransparent, aiTextureType_OPACITY); + if (!effect.mTexTransparent.mName.empty()) + AddTexture(mat, pParser, effect, effect.mTexTransparent, aiTextureType_OPACITY); - if( !effect.mTexReflective.mName.empty()) - AddTexture( mat, pParser, effect, effect.mTexReflective, aiTextureType_REFLECTION); + if (!effect.mTexReflective.mName.empty()) + AddTexture(mat, pParser, effect, effect.mTexReflective, aiTextureType_REFLECTION); } } // ------------------------------------------------------------------------------------------------ // Constructs materials from the collada material definitions -void ColladaLoader::BuildMaterials( ColladaParser& pParser, aiScene* /*pScene*/) +void ColladaLoader::BuildMaterials(ColladaParser& pParser, aiScene* /*pScene*/) { newMats.reserve(pParser.mMaterialLibrary.size()); - for( ColladaParser::MaterialLibrary::const_iterator matIt = pParser.mMaterialLibrary.begin(); + for (ColladaParser::MaterialLibrary::const_iterator matIt = pParser.mMaterialLibrary.begin(); matIt != pParser.mMaterialLibrary.end(); ++matIt) { const Collada::Material& material = matIt->second; // a material is only a reference to an effect - ColladaParser::EffectLibrary::iterator effIt = pParser.mEffectLibrary.find( material.mEffect); - if( effIt == pParser.mEffectLibrary.end()) + ColladaParser::EffectLibrary::iterator effIt = pParser.mEffectLibrary.find(material.mEffect); + if (effIt == pParser.mEffectLibrary.end()) continue; Collada::Effect& effect = effIt->second; // create material aiMaterial* mat = new aiMaterial; - aiString name( material.mName.empty() ? matIt->first : material.mName ); - mat->AddProperty(&name,AI_MATKEY_NAME); + aiString name(material.mName.empty() ? matIt->first : material.mName); + mat->AddProperty(&name, AI_MATKEY_NAME); // store the material mMaterialIndexByName[matIt->first] = newMats.size(); - newMats.push_back( std::pair( &effect,mat) ); + newMats.push_back(std::pair(&effect, mat)); } // ScenePreprocessor generates a default material automatically if none is there. // All further code here in this loader works well without a valid material so // we can safely let it to ScenePreprocessor. #if 0 - if( newMats.size() == 0) + if (newMats.size() == 0) { aiMaterial* mat = new aiMaterial; - aiString name( AI_DEFAULT_MATERIAL_NAME ); - mat->AddProperty( &name, AI_MATKEY_NAME); + aiString name(AI_DEFAULT_MATERIAL_NAME); + mat->AddProperty(&name, AI_MATKEY_NAME); const int shadeMode = aiShadingMode_Phong; - mat->AddProperty( &shadeMode, 1, AI_MATKEY_SHADING_MODEL); - aiColor4D colAmbient( 0.2, 0.2, 0.2, 1.0), colDiffuse( 0.8, 0.8, 0.8, 1.0), colSpecular( 0.5, 0.5, 0.5, 0.5); - mat->AddProperty( &colAmbient, 1, AI_MATKEY_COLOR_AMBIENT); - mat->AddProperty( &colDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE); - mat->AddProperty( &colSpecular, 1, AI_MATKEY_COLOR_SPECULAR); + mat->AddProperty(&shadeMode, 1, AI_MATKEY_SHADING_MODEL); + aiColor4D colAmbient(0.2, 0.2, 0.2, 1.0), colDiffuse(0.8, 0.8, 0.8, 1.0), colSpecular(0.5, 0.5, 0.5, 0.5); + mat->AddProperty(&colAmbient, 1, AI_MATKEY_COLOR_AMBIENT); + mat->AddProperty(&colDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE); + mat->AddProperty(&colSpecular, 1, AI_MATKEY_COLOR_SPECULAR); const ai_real specExp = 5.0; - mat->AddProperty( &specExp, 1, AI_MATKEY_SHININESS); - } + mat->AddProperty(&specExp, 1, AI_MATKEY_SHININESS); +} #endif } // ------------------------------------------------------------------------------------------------ // Resolves the texture name for the given effect texture entry -aiString ColladaLoader::FindFilenameForEffectTexture( const ColladaParser& pParser, +aiString ColladaLoader::FindFilenameForEffectTexture(const ColladaParser& pParser, const Collada::Effect& pEffect, const std::string& pName) { aiString result; // recurse through the param references until we end up at an image std::string name = pName; - while( 1) + while (1) { // the given string is a param entry. Find it - Collada::Effect::ParamLibrary::const_iterator it = pEffect.mParams.find( name); + Collada::Effect::ParamLibrary::const_iterator it = pEffect.mParams.find(name); // if not found, we're at the end of the recursion. The resulting string should be the image ID - if( it == pEffect.mParams.end()) + if (it == pEffect.mParams.end()) break; // else recurse on @@ -1748,8 +1755,8 @@ aiString ColladaLoader::FindFilenameForEffectTexture( const ColladaParser& pPars } // find the image referred by this name in the image library of the scene - ColladaParser::ImageLibrary::const_iterator imIt = pParser.mImageLibrary.find( name); - if( imIt == pParser.mImageLibrary.end()) + ColladaParser::ImageLibrary::const_iterator imIt = pParser.mImageLibrary.find(name); + if (imIt == pParser.mImageLibrary.end()) { ASSIMP_LOG_WARN_F("Collada: Unable to resolve effect texture entry \"", pName, "\", ended up at ID \"", name, "\"."); @@ -1760,41 +1767,41 @@ aiString ColladaLoader::FindFilenameForEffectTexture( const ColladaParser& pPars } // if this is an embedded texture image setup an aiTexture for it - if (imIt->second.mFileName.empty()) + if (!imIt->second.mImageData.empty()) { - if (imIt->second.mImageData.empty()) { - throw DeadlyImportError("Collada: Invalid texture, no data or file reference given"); - } - aiTexture* tex = new aiTexture(); + // Store embedded texture name reference + tex->mFilename.Set(imIt->second.mFileName.c_str()); + result.Set(imIt->second.mFileName); + + // TODO: check the possibility of using the flag "AI_CONFIG_IMPORT_FBX_EMBEDDED_TEXTURES_LEGACY_NAMING" +// result.data[0] = '*'; +// result.length = 1 + ASSIMP_itoa10(result.data + 1, static_cast(MAXLEN - 1), static_cast(mTextures.size())); + + // setup format hint if (imIt->second.mEmbeddedFormat.length() > 3) { ASSIMP_LOG_WARN("Collada: texture format hint is too long, truncating to 3 characters"); } - strncpy(tex->achFormatHint,imIt->second.mEmbeddedFormat.c_str(),3); + strncpy(tex->achFormatHint, imIt->second.mEmbeddedFormat.c_str(), 3); // and copy texture data tex->mHeight = 0; tex->mWidth = static_cast(imIt->second.mImageData.size()); tex->pcData = (aiTexel*)new char[tex->mWidth]; - memcpy(tex->pcData,&imIt->second.mImageData[0],tex->mWidth); - - // TODO: check the possibility of using the flag "AI_CONFIG_IMPORT_FBX_EMBEDDED_TEXTURES_LEGACY_NAMING" - // In FBX files textures are now stored internally by Assimp with their filename included - // Now Assimp can lookup through the loaded textures after all data is processed - // We need to load all textures before referencing them, as FBX file format order may reference a texture before loading it - // This may occur on this case too, it has to be studied - // setup texture reference string - result.data[0] = '*'; - result.length = 1 + ASSIMP_itoa10(result.data+1,static_cast(MAXLEN-1),static_cast(mTextures.size())); + memcpy(tex->pcData, &imIt->second.mImageData[0], tex->mWidth); // and add this texture to the list mTextures.push_back(tex); } else { - result.Set( imIt->second.mFileName ); + if (imIt->second.mFileName.empty()) { + throw DeadlyImportError("Collada: Invalid texture, no data or file reference given"); + } + + result.Set(imIt->second.mFileName); ConvertPath(result); } return result; @@ -1802,77 +1809,78 @@ aiString ColladaLoader::FindFilenameForEffectTexture( const ColladaParser& pPars // ------------------------------------------------------------------------------------------------ // Convert a path read from a collada file to the usual representation -void ColladaLoader::ConvertPath (aiString& ss) +void ColladaLoader::ConvertPath(aiString& ss) { // TODO: collada spec, p 22. Handle URI correctly. // For the moment we're just stripping the file:// away to make it work. // Windows doesn't seem to be able to find stuff like // 'file://..\LWO\LWO2\MappingModes\earthSpherical.jpg' - if (0 == strncmp(ss.data,"file://",7)) + if (0 == strncmp(ss.data, "file://", 7)) { ss.length -= 7; - memmove(ss.data,ss.data+7,ss.length); + memmove(ss.data, ss.data + 7, ss.length); ss.data[ss.length] = '\0'; } - // Maxon Cinema Collada Export writes "file:///C:\andsoon" with three slashes... - // I need to filter it without destroying linux paths starting with "/somewhere" + // Maxon Cinema Collada Export writes "file:///C:\andsoon" with three slashes... + // I need to filter it without destroying linux paths starting with "/somewhere" #if defined( _MSC_VER ) - if( ss.data[0] == '/' && isalpha( (unsigned char) ss.data[1]) && ss.data[2] == ':' ) { + if (ss.data[0] == '/' && isalpha((unsigned char)ss.data[1]) && ss.data[2] == ':') { #else - if (ss.data[ 0 ] == '/' && isalpha( ss.data[ 1 ] ) && ss.data[ 2 ] == ':') { + if (ss.data[0] == '/' && isalpha(ss.data[1]) && ss.data[2] == ':') { #endif - --ss.length; - ::memmove( ss.data, ss.data+1, ss.length); - ss.data[ss.length] = 0; - } - - // find and convert all %xy special chars - char* out = ss.data; - for( const char* it = ss.data; it != ss.data + ss.length; /**/ ) - { - if( *it == '%' && (it + 3) < ss.data + ss.length ) - { - // separate the number to avoid dragging in chars from behind into the parsing - char mychar[3] = { it[1], it[2], 0 }; - size_t nbr = strtoul16( mychar); - it += 3; - *out++ = (char)(nbr & 0xFF); - } else - { - *out++ = *it++; + --ss.length; + ::memmove(ss.data, ss.data + 1, ss.length); + ss.data[ss.length] = 0; } - } - // adjust length and terminator of the shortened string - *out = 0; - ss.length = (ptrdiff_t) (out - ss.data); + // find and convert all %xy special chars + char* out = ss.data; + for (const char* it = ss.data; it != ss.data + ss.length; /**/) + { + if (*it == '%' && (it + 3) < ss.data + ss.length) + { + // separate the number to avoid dragging in chars from behind into the parsing + char mychar[3] = { it[1], it[2], 0 }; + size_t nbr = strtoul16(mychar); + it += 3; + *out++ = (char)(nbr & 0xFF); + } + else + { + *out++ = *it++; + } + } + + // adjust length and terminator of the shortened string + *out = 0; + ss.length = (ptrdiff_t)(out - ss.data); } // ------------------------------------------------------------------------------------------------ // Reads a float value from an accessor and its data array. -ai_real ColladaLoader::ReadFloat( const Collada::Accessor& pAccessor, const Collada::Data& pData, size_t pIndex, size_t pOffset) const +ai_real ColladaLoader::ReadFloat(const Collada::Accessor& pAccessor, const Collada::Data& pData, size_t pIndex, size_t pOffset) const { // FIXME: (thom) Test for data type here in every access? For the moment, I leave this to the caller size_t pos = pAccessor.mStride * pIndex + pAccessor.mOffset + pOffset; - ai_assert( pos < pData.mValues.size()); + ai_assert(pos < pData.mValues.size()); return pData.mValues[pos]; } // ------------------------------------------------------------------------------------------------ // Reads a string value from an accessor and its data array. -const std::string& ColladaLoader::ReadString( const Collada::Accessor& pAccessor, const Collada::Data& pData, size_t pIndex) const +const std::string& ColladaLoader::ReadString(const Collada::Accessor& pAccessor, const Collada::Data& pData, size_t pIndex) const { size_t pos = pAccessor.mStride * pIndex + pAccessor.mOffset; - ai_assert( pos < pData.mStrings.size()); + ai_assert(pos < pData.mStrings.size()); return pData.mStrings[pos]; } // ------------------------------------------------------------------------------------------------ // Collects all nodes into the given array -void ColladaLoader::CollectNodes( const aiNode* pNode, std::vector& poNodes) const +void ColladaLoader::CollectNodes(const aiNode* pNode, std::vector& poNodes) const { - poNodes.push_back( pNode); + poNodes.push_back(pNode); for (size_t a = 0; a < pNode->mNumChildren; ++a) { CollectNodes(pNode->mChildren[a], poNodes); } @@ -1880,15 +1888,15 @@ void ColladaLoader::CollectNodes( const aiNode* pNode, std::vectormName == pName || pNode->mID == pName) + if (pNode->mName == pName || pNode->mID == pName) return pNode; - for( size_t a = 0; a < pNode->mChildren.size(); ++a) + for (size_t a = 0; a < pNode->mChildren.size(); ++a) { - const Collada::Node* node = FindNode( pNode->mChildren[a], pName); - if( node) + const Collada::Node* node = FindNode(pNode->mChildren[a], pName); + if (node) return node; } @@ -1897,43 +1905,57 @@ const Collada::Node* ColladaLoader::FindNode( const Collada::Node* pNode, const // ------------------------------------------------------------------------------------------------ // Finds a node in the collada scene by the given SID -const Collada::Node* ColladaLoader::FindNodeBySID( const Collada::Node* pNode, const std::string& pSID) const -{ - if( pNode->mSID == pSID) - return pNode; +const Collada::Node* ColladaLoader::FindNodeBySID( const Collada::Node* pNode, const std::string& pSID) const { + if (nullptr == pNode) { + return nullptr; + } - for( size_t a = 0; a < pNode->mChildren.size(); ++a) - { - const Collada::Node* node = FindNodeBySID( pNode->mChildren[a], pSID); - if( node) - return node; - } + if (pNode->mSID == pSID) { + return pNode; + } - return NULL; + for( size_t a = 0; a < pNode->mChildren.size(); ++a) { + const Collada::Node* node = FindNodeBySID( pNode->mChildren[a], pSID); + if (node) { + return node; + } + } + + return nullptr; } // ------------------------------------------------------------------------------------------------ // Finds a proper unique name for a node derived from the collada-node's properties. // The name must be unique for proper node-bone association. -std::string ColladaLoader::FindNameForNode( const Collada::Node* pNode) +std::string ColladaLoader::FindNameForNode(const Collada::Node* pNode) { // If explicitly requested, just use the collada name. - if (useColladaName) { - return pNode->mName; - } - - // Now setup the name of the assimp node. The collada name might not be - // unique, so we use the collada ID. - if (!pNode->mID.empty()) - return pNode->mID; - else if (!pNode->mSID.empty()) - return pNode->mSID; - else + if (useColladaName) { - // No need to worry. Unnamed nodes are no problem at all, except - // if cameras or lights need to be assigned to them. - return format() << "$ColladaAutoName$_" << mNodeNameCounter++; + if (!pNode->mName.empty()) { + return pNode->mName; + } + else { + return format() << "$ColladaAutoName$_" << mNodeNameCounter++; + } + } + else + { + // Now setup the name of the assimp node. The collada name might not be + // unique, so we use the collada ID. + if (!pNode->mID.empty()) + return pNode->mID; + else if (!pNode->mSID.empty()) + return pNode->mSID; + else + { + // No need to worry. Unnamed nodes are no problem at all, except + // if cameras or lights need to be assigned to them. + return format() << "$ColladaAutoName$_" << mNodeNameCounter++; + } } } +} // Namespace Assimp + #endif // !! ASSIMP_BUILD_NO_DAE_IMPORTER diff --git a/third_party/libassimp/code/ColladaLoader.h b/third_party/libassimp/code/Collada/ColladaLoader.h similarity index 97% rename from third_party/libassimp/code/ColladaLoader.h rename to third_party/libassimp/code/Collada/ColladaLoader.h index d61845b245..dce46e06f6 100644 --- a/third_party/libassimp/code/ColladaLoader.h +++ b/third_party/libassimp/code/Collada/ColladaLoader.h @@ -4,7 +4,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -94,20 +94,20 @@ public: public: /** Returns whether the class can handle the format of the given file. * See BaseImporter::CanRead() for details. */ - bool CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const; + bool CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const override; protected: /** Return importer meta information. * See #BaseImporter::GetInfo for the details */ - const aiImporterDesc* GetInfo () const; + const aiImporterDesc* GetInfo () const override; - void SetupProperties(const Importer* pImp); + void SetupProperties(const Importer* pImp) override; /** Imports the given file into the given scene structure. * See BaseImporter::InternReadFile() for details */ - void InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler); + void InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) override; /** Recursively constructs a scene node for the given parser node and returns it. */ aiNode* BuildHierarchy( const ColladaParser& pParser, const Collada::Node* pNode); @@ -120,7 +120,7 @@ protected: void BuildMeshesForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget); - aiMesh *findMesh(std::string meshid); + aiMesh *findMesh(const std::string& meshid); /** 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, diff --git a/third_party/libassimp/code/ColladaParser.cpp b/third_party/libassimp/code/Collada/ColladaParser.cpp similarity index 50% rename from third_party/libassimp/code/ColladaParser.cpp rename to third_party/libassimp/code/Collada/ColladaParser.cpp index 052cd51c46..646ec473db 100644 --- a/third_party/libassimp/code/ColladaParser.cpp +++ b/third_party/libassimp/code/Collada/ColladaParser.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -57,6 +57,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include +#include #include @@ -66,9 +67,9 @@ using namespace Assimp::Formatter; // ------------------------------------------------------------------------------------------------ // Constructor to be privately used by Importer -ColladaParser::ColladaParser( IOSystem* pIOHandler, const std::string& pFile) - : mFileName( pFile ) - , mReader( nullptr ) +ColladaParser::ColladaParser(IOSystem* pIOHandler, const std::string& pFile) + : mFileName(pFile) + , mReader(nullptr) , mDataLibrary() , mAccessorLibrary() , mMeshLibrary() @@ -79,32 +80,60 @@ ColladaParser::ColladaParser( IOSystem* pIOHandler, const std::string& pFile) , mLightLibrary() , mCameraLibrary() , mControllerLibrary() - , mRootNode( nullptr ) + , mRootNode(nullptr) , mAnims() - , mUnitSize( 1.0f ) - , mUpDirection( UP_Y ) - , mFormat(FV_1_5_n ) // We assume the newest file format by default + , mUnitSize(1.0f) + , mUpDirection(UP_Y) + , mFormat(FV_1_5_n) // We assume the newest file format by default { // validate io-handler instance - if (nullptr == pIOHandler ) { - throw DeadlyImportError("IOSystem is NULL." ); + if (nullptr == pIOHandler) { + throw DeadlyImportError("IOSystem is NULL."); } - // open the file - std::unique_ptr file( pIOHandler->Open(pFile ) ); - if (file.get() == nullptr) { - throw DeadlyImportError( "Failed to open file " + pFile + "." ); + std::unique_ptr daefile; + std::unique_ptr zip_archive; + + // Determine type + std::string extension = BaseImporter::GetExtension(pFile); + if (extension != "dae") { + zip_archive.reset(new ZipArchiveIOSystem(pIOHandler, pFile)); + } + + if (zip_archive && zip_archive->isOpen()) { + std::string dae_filename = ReadZaeManifest(*zip_archive); + + if (dae_filename.empty()) { + ThrowException(std::string("Invalid ZAE")); + } + + daefile.reset(zip_archive->Open(dae_filename.c_str())); + if (daefile == nullptr) { + ThrowException(std::string("Invalid ZAE manifest: '") + std::string(dae_filename) + std::string("' is missing")); + } + } + else { + // attempt to open the file directly + daefile.reset(pIOHandler->Open(pFile)); + if (daefile.get() == nullptr) { + throw DeadlyImportError("Failed to open file '" + pFile + "'."); + } } // generate a XML reader for it - std::unique_ptr mIOWrapper(new CIrrXML_IOStreamReader(file.get())); - mReader = irr::io::createIrrXMLReader( mIOWrapper.get()); + std::unique_ptr mIOWrapper(new CIrrXML_IOStreamReader(daefile.get())); + mReader = irr::io::createIrrXMLReader(mIOWrapper.get()); if (!mReader) { - ThrowException("Collada: Unable to open file."); + ThrowException("Unable to read file, malformed XML"); } // start reading ReadContents(); + + // read embedded textures + if (zip_archive && zip_archive->isOpen()) { + ReadEmbeddedTextures(*zip_archive); + } } // ------------------------------------------------------------------------------------------------ @@ -112,18 +141,61 @@ ColladaParser::ColladaParser( IOSystem* pIOHandler, const std::string& pFile) ColladaParser::~ColladaParser() { delete mReader; - for( NodeLibrary::iterator it = mNodeLibrary.begin(); it != mNodeLibrary.end(); ++it) + for (NodeLibrary::iterator it = mNodeLibrary.begin(); it != mNodeLibrary.end(); ++it) delete it->second; - for( MeshLibrary::iterator it = mMeshLibrary.begin(); it != mMeshLibrary.end(); ++it) + for (MeshLibrary::iterator it = mMeshLibrary.begin(); it != mMeshLibrary.end(); ++it) delete it->second; } +// ------------------------------------------------------------------------------------------------ +// Read a ZAE manifest and return the filename to attempt to open +std::string ColladaParser::ReadZaeManifest(ZipArchiveIOSystem &zip_archive) { + // Open the manifest + std::unique_ptr manifestfile(zip_archive.Open("manifest.xml")); + if (manifestfile == nullptr) + { + // No manifest, hope there is only one .DAE inside + std::vector file_list; + zip_archive.getFileListExtension(file_list, "dae"); + + if (file_list.empty()) + return std::string(); + + return file_list.front(); + } + + std::unique_ptr mIOWrapper(new CIrrXML_IOStreamReader(manifestfile.get())); + std::unique_ptr manifest_reader(irr::io::createIrrXMLReader(mIOWrapper.get())); + + while (manifest_reader->read()) + { + // find the manifest "dae_root" element + if (manifest_reader->getNodeType() == irr::io::EXN_ELEMENT) + { + if (::strcmp(manifest_reader->getNodeName(), "dae_root") == 0) + { + if (!manifest_reader->read()) + return std::string(); + if (manifest_reader->getNodeType() != irr::io::EXN_TEXT && manifest_reader->getNodeType() != irr::io::EXN_CDATA) + return std::string(); + + const char* filepath = manifest_reader->getNodeData(); + if (filepath == nullptr) + return std::string(); + + return std::string(filepath); + } + } + } + return std::string(); +} + // ------------------------------------------------------------------------------------------------ // Read bool from text contents of current element bool ColladaParser::ReadBoolFromTextContent() { const char* cur = GetTextContent(); - return (!ASSIMP_strincmp(cur,"true",4) || '0' != *cur); + return (!ASSIMP_strincmp(cur, "true", 4) || '0' != *cur); } // ------------------------------------------------------------------------------------------------ @@ -138,39 +210,41 @@ ai_real ColladaParser::ReadFloatFromTextContent() // Reads the contents of the file void ColladaParser::ReadContents() { - while( mReader->read()) + while (mReader->read()) { // handle the root element "COLLADA" - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "COLLADA")) + if (IsElement("COLLADA")) { // check for 'version' attribute const int attrib = TestAttribute("version"); if (attrib != -1) { const char* version = mReader->getAttributeValue(attrib); - if (!::strncmp(version,"1.5",3)) { - mFormat = FV_1_5_n; + if (!::strncmp(version, "1.5", 3)) { + mFormat = FV_1_5_n; ASSIMP_LOG_DEBUG("Collada schema version is 1.5.n"); } - else if (!::strncmp(version,"1.4",3)) { - mFormat = FV_1_4_n; + else if (!::strncmp(version, "1.4", 3)) { + mFormat = FV_1_4_n; ASSIMP_LOG_DEBUG("Collada schema version is 1.4.n"); } - else if (!::strncmp(version,"1.3",3)) { - mFormat = FV_1_3_n; + else if (!::strncmp(version, "1.3", 3)) { + mFormat = FV_1_3_n; ASSIMP_LOG_DEBUG("Collada schema version is 1.3.n"); } } ReadStructure(); - } else + } + else { - ASSIMP_LOG_DEBUG_F( "Ignoring global element <", mReader->getNodeName(), ">." ); + ASSIMP_LOG_DEBUG_F("Ignoring global element <", mReader->getNodeName(), ">."); SkipElement(); } - } else + } + else { // skip everything else silently } @@ -181,47 +255,47 @@ void ColladaParser::ReadContents() // Reads the structure of the file void ColladaParser::ReadStructure() { - while( mReader->read()) + while (mReader->read()) { // beginning of elements - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "asset")) + if (IsElement("asset")) ReadAssetInfo(); - else if( IsElement( "library_animations")) + else if (IsElement("library_animations")) ReadAnimationLibrary(); - else if (IsElement("library_animation_clips")) - ReadAnimationClipLibrary(); - else if( IsElement( "library_controllers")) + else if (IsElement("library_animation_clips")) + ReadAnimationClipLibrary(); + else if (IsElement("library_controllers")) ReadControllerLibrary(); - else if( IsElement( "library_images")) + else if (IsElement("library_images")) ReadImageLibrary(); - else if( IsElement( "library_materials")) + else if (IsElement("library_materials")) ReadMaterialLibrary(); - else if( IsElement( "library_effects")) + else if (IsElement("library_effects")) ReadEffectLibrary(); - else if( IsElement( "library_geometries")) + else if (IsElement("library_geometries")) ReadGeometryLibrary(); - else if( IsElement( "library_visual_scenes")) + else if (IsElement("library_visual_scenes")) ReadSceneLibrary(); - else if( IsElement( "library_lights")) + else if (IsElement("library_lights")) ReadLightLibrary(); - else if( IsElement( "library_cameras")) + else if (IsElement("library_cameras")) ReadCameraLibrary(); - else if( IsElement( "library_nodes")) + else if (IsElement("library_nodes")) ReadSceneNode(NULL); /* some hacking to reuse this piece of code */ - else if( IsElement( "scene")) + else if (IsElement("scene")) ReadScene(); else SkipElement(); } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { break; } } - PostProcessRootAnimations(); + PostProcessRootAnimations(); PostProcessControllers(); } @@ -229,136 +303,208 @@ void ColladaParser::ReadStructure() // Reads asset information such as coordinate system information and legal blah void ColladaParser::ReadAssetInfo() { - if( mReader->isEmptyElement()) + if (mReader->isEmptyElement()) return; - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "unit")) + if (IsElement("unit")) { // read unit data from the element's attributes - const int attrIndex = TestAttribute( "meter"); + const int attrIndex = TestAttribute("meter"); if (attrIndex == -1) { mUnitSize = 1.f; } else { - mUnitSize = mReader->getAttributeValueAsFloat( attrIndex); + mUnitSize = mReader->getAttributeValueAsFloat(attrIndex); } // consume the trailing stuff - if( !mReader->isEmptyElement()) + if (!mReader->isEmptyElement()) SkipElement(); } - else if( IsElement( "up_axis")) + else if (IsElement("up_axis")) { // read content, strip whitespace, compare const char* content = GetTextContent(); - if( strncmp( content, "X_UP", 4) == 0) + if (strncmp(content, "X_UP", 4) == 0) mUpDirection = UP_X; - else if( strncmp( content, "Z_UP", 4) == 0) + else if (strncmp(content, "Z_UP", 4) == 0) mUpDirection = UP_Z; else mUpDirection = UP_Y; // check element end - TestClosing( "up_axis"); - } else + TestClosing("up_axis"); + } + else if (IsElement("contributor")) { - SkipElement(); + ReadContributorInfo(); + } + else + { + ReadMetaDataItem(mAssetMetaData); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "asset") != 0) - ThrowException( "Expected end of element."); + if (strcmp(mReader->getNodeName(), "asset") != 0) + ThrowException("Expected end of element."); break; } } } +// ------------------------------------------------------------------------------------------------ +// Reads the contributor info +void ColladaParser::ReadContributorInfo() +{ + if (mReader->isEmptyElement()) + return; + + while (mReader->read()) + { + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) + { + ReadMetaDataItem(mAssetMetaData); + } + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + { + if (strcmp(mReader->getNodeName(), "contributor") != 0) + ThrowException("Expected end of element."); + break; + } + } +} + +// ------------------------------------------------------------------------------------------------ +// Reads a single string metadata item +void ColladaParser::ReadMetaDataItem(StringMetaData &metadata) +{ + // Metadata such as created, keywords, subject etc + const char* key_char = mReader->getNodeName(); + if (key_char != nullptr) + { + const std::string key_str(key_char); + const char* value_char = TestTextContent(); + if (value_char != nullptr) + { + std::string camel_key_str = key_str; + ToCamelCase(camel_key_str); + aiString aistr; + aistr.Set(value_char); + metadata.emplace(camel_key_str, aistr); + } + TestClosing(key_str.c_str()); + } + else + SkipElement(); +} + +// ------------------------------------------------------------------------------------------------ +// Convert underscore_seperated to CamelCase: "authoring_tool" becomes "AuthoringTool" +void ColladaParser::ToCamelCase(std::string &text) +{ + if (text.empty()) + return; + // Capitalise first character + text[0] = ToUpper(text[0]); + for (auto it = text.begin(); it != text.end(); /*iterated below*/) + { + if ((*it) == '_') + { + it = text.erase(it); + if (it != text.end()) + (*it) = ToUpper(*it); + } + else + ++it; + } +} + // ------------------------------------------------------------------------------------------------ // Reads the animation clips void ColladaParser::ReadAnimationClipLibrary() { - if (mReader->isEmptyElement()) - return; + if (mReader->isEmptyElement()) + return; - while (mReader->read()) - { - if (mReader->getNodeType() == irr::io::EXN_ELEMENT) - { - if (IsElement("animation_clip")) - { - // optional name given as an attribute - std::string animName; - int indexName = TestAttribute("name"); - int indexID = TestAttribute("id"); - if (indexName >= 0) - animName = mReader->getAttributeValue(indexName); - else if (indexID >= 0) - animName = mReader->getAttributeValue(indexID); - else - animName = std::string("animation_") + to_string(mAnimationClipLibrary.size()); + while (mReader->read()) + { + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) + { + if (IsElement("animation_clip")) + { + // optional name given as an attribute + std::string animName; + int indexName = TestAttribute("name"); + int indexID = TestAttribute("id"); + if (indexName >= 0) + animName = mReader->getAttributeValue(indexName); + else if (indexID >= 0) + animName = mReader->getAttributeValue(indexID); + else + animName = std::string("animation_") + to_string(mAnimationClipLibrary.size()); - std::pair > clip; + std::pair > clip; - clip.first = animName; + clip.first = animName; - while (mReader->read()) - { - if (mReader->getNodeType() == irr::io::EXN_ELEMENT) - { - if (IsElement("instance_animation")) - { - int indexUrl = TestAttribute("url"); - if (indexUrl >= 0) - { - const char* url = mReader->getAttributeValue(indexUrl); - if (url[0] != '#') - ThrowException("Unknown reference format"); + while (mReader->read()) + { + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) + { + if (IsElement("instance_animation")) + { + int indexUrl = TestAttribute("url"); + if (indexUrl >= 0) + { + const char* url = mReader->getAttributeValue(indexUrl); + if (url[0] != '#') + ThrowException("Unknown reference format"); - url++; + url++; - clip.second.push_back(url); - } - } - else - { - // ignore the rest - SkipElement(); - } - } - else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) - { - if (strcmp(mReader->getNodeName(), "animation_clip") != 0) - ThrowException("Expected end of element."); + clip.second.push_back(url); + } + } + else + { + // ignore the rest + SkipElement(); + } + } + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + { + if (strcmp(mReader->getNodeName(), "animation_clip") != 0) + ThrowException("Expected end of element."); - break; - } - } + break; + } + } - if (clip.second.size() > 0) - { - mAnimationClipLibrary.push_back(clip); - } - } - else - { - // ignore the rest - SkipElement(); - } - } - else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) - { - if (strcmp(mReader->getNodeName(), "library_animation_clips") != 0) - ThrowException("Expected end of element."); + if (clip.second.size() > 0) + { + mAnimationClipLibrary.push_back(clip); + } + } + else + { + // ignore the rest + SkipElement(); + } + } + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + { + if (strcmp(mReader->getNodeName(), "library_animation_clips") != 0) + ThrowException("Expected end of element."); - break; - } - } + break; + } + } } void ColladaParser::PostProcessControllers() @@ -367,11 +513,11 @@ void ColladaParser::PostProcessControllers() for (ControllerLibrary::iterator it = mControllerLibrary.begin(); it != mControllerLibrary.end(); ++it) { meshId = it->second.mMeshId; ControllerLibrary::iterator findItr = mControllerLibrary.find(meshId); - while(findItr != mControllerLibrary.end()) { + while (findItr != mControllerLibrary.end()) { meshId = findItr->second.mMeshId; findItr = mControllerLibrary.find(meshId); } - + it->second.mMeshId = meshId; } } @@ -380,43 +526,43 @@ void ColladaParser::PostProcessControllers() // Re-build animations from animation clip library, if present, otherwise combine single-channel animations void ColladaParser::PostProcessRootAnimations() { - if (mAnimationClipLibrary.size() > 0) - { - Animation temp; + if (mAnimationClipLibrary.size() > 0) + { + Animation temp; - for (AnimationClipLibrary::iterator it = mAnimationClipLibrary.begin(); it != mAnimationClipLibrary.end(); ++it) - { - std::string clipName = it->first; + for (AnimationClipLibrary::iterator it = mAnimationClipLibrary.begin(); it != mAnimationClipLibrary.end(); ++it) + { + std::string clipName = it->first; - Animation *clip = new Animation(); - clip->mName = clipName; + Animation *clip = new Animation(); + clip->mName = clipName; - temp.mSubAnims.push_back(clip); + temp.mSubAnims.push_back(clip); - for (std::vector::iterator a = it->second.begin(); a != it->second.end(); ++a) - { - std::string animationID = *a; + for (std::vector::iterator a = it->second.begin(); a != it->second.end(); ++a) + { + std::string animationID = *a; - AnimationLibrary::iterator animation = mAnimationLibrary.find(animationID); + AnimationLibrary::iterator animation = mAnimationLibrary.find(animationID); - if (animation != mAnimationLibrary.end()) - { - Animation *pSourceAnimation = animation->second; + if (animation != mAnimationLibrary.end()) + { + Animation *pSourceAnimation = animation->second; - pSourceAnimation->CollectChannelsRecursively(clip->mChannels); - } - } - } + pSourceAnimation->CollectChannelsRecursively(clip->mChannels); + } + } + } - mAnims = temp; + mAnims = temp; - // Ensure no double deletes. - temp.mSubAnims.clear(); - } - else - { - mAnims.CombineSingleChannelAnimations(); - } + // Ensure no double deletes. + temp.mSubAnims.clear(); + } + else + { + mAnims.CombineSingleChannelAnimations(); + } } // ------------------------------------------------------------------------------------------------ @@ -426,24 +572,25 @@ void ColladaParser::ReadAnimationLibrary() if (mReader->isEmptyElement()) return; - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "animation")) + if (IsElement("animation")) { // delegate the reading. Depending on the inner elements it will be a container or a anim channel - ReadAnimation( &mAnims); - } else + ReadAnimation(&mAnims); + } + else { // ignore the rest SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "library_animations") != 0) - ThrowException( "Expected end of element."); + if (strcmp(mReader->getNodeName(), "library_animations") != 0) + ThrowException("Expected end of element."); break; } @@ -452,9 +599,9 @@ void ColladaParser::ReadAnimationLibrary() // ------------------------------------------------------------------------------------------------ // Reads an animation into the given parent structure -void ColladaParser::ReadAnimation( Collada::Animation* pParent) +void ColladaParser::ReadAnimation(Collada::Animation* pParent) { - if( mReader->isEmptyElement()) + if (mReader->isEmptyElement()) return; // an element may be a container for grouping sub-elements or an animation channel @@ -466,68 +613,68 @@ void ColladaParser::ReadAnimation( Collada::Animation* pParent) // optional name given as an attribute std::string animName; - std::string animID; - int indexName = TestAttribute( "name"); - int indexID = TestAttribute( "id"); + std::string animID; + int indexName = TestAttribute("name"); + int indexID = TestAttribute("id"); - if (indexID >= 0) - animID = mReader->getAttributeValue(indexID); + if (indexID >= 0) + animID = mReader->getAttributeValue(indexID); - if( indexName >= 0) - animName = mReader->getAttributeValue( indexName); - else if( indexID >= 0) + if (indexName >= 0) + animName = mReader->getAttributeValue(indexName); + else if (indexID >= 0) animName = animID; else animName = "animation"; - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { // we have subanimations - if( IsElement( "animation")) + if (IsElement("animation")) { // create container from our element - if( !anim) + if (!anim) { anim = new Animation; anim->mName = animName; - pParent->mSubAnims.push_back( anim); + pParent->mSubAnims.push_back(anim); } // recurse into the subelement - ReadAnimation( anim); + ReadAnimation(anim); } - else if( IsElement( "source")) + else if (IsElement("source")) { // possible animation data - we'll never know. Better store it ReadSource(); } - else if( IsElement( "sampler")) + else if (IsElement("sampler")) { // read the ID to assign the corresponding collada channel afterwards. - int indexID = GetAttribute( "id"); - std::string id = mReader->getAttributeValue( indexID); - ChannelMap::iterator newChannel = channels.insert( std::make_pair( id, AnimationChannel())).first; + int indexID = GetAttribute("id"); + std::string id = mReader->getAttributeValue(indexID); + ChannelMap::iterator newChannel = channels.insert(std::make_pair(id, AnimationChannel())).first; // have it read into a channel - ReadAnimationSampler( newChannel->second); + ReadAnimationSampler(newChannel->second); } - else if( IsElement( "channel")) + else if (IsElement("channel")) { // the binding element whose whole purpose is to provide the target to animate // Thanks, Collada! A directly posted information would have been too simple, I guess. // Better add another indirection to that! Can't have enough of those. - int indexTarget = GetAttribute( "target"); - int indexSource = GetAttribute( "source"); - const char* sourceId = mReader->getAttributeValue( indexSource); - if( sourceId[0] == '#') + int indexTarget = GetAttribute("target"); + int indexSource = GetAttribute("source"); + const char* sourceId = mReader->getAttributeValue(indexSource); + if (sourceId[0] == '#') sourceId++; - ChannelMap::iterator cit = channels.find( sourceId); - if( cit != channels.end()) - cit->second.mTarget = mReader->getAttributeValue( indexTarget); + ChannelMap::iterator cit = channels.find(sourceId); + if (cit != channels.end()) + cit->second.mTarget = mReader->getAttributeValue(indexTarget); - if( !mReader->isEmptyElement()) + if (!mReader->isEmptyElement()) SkipElement(); } else @@ -536,24 +683,24 @@ void ColladaParser::ReadAnimation( Collada::Animation* pParent) SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "animation") != 0) - ThrowException( "Expected end of element."); + if (strcmp(mReader->getNodeName(), "animation") != 0) + ThrowException("Expected end of element."); break; } } // it turned out to have channels - add them - if( !channels.empty()) + if (!channels.empty()) { - // FIXME: Is this essentially doing the same as "single-anim-node" codepath in - // ColladaLoader::StoreAnimations? For now, this has been deferred to after - // all animations and all clips have been read. Due to handling of - // this cannot be done here, as the channel owner - // is lost, and some exporters make up animations by referring to multiple - // single-channel animations from an . + // FIXME: Is this essentially doing the same as "single-anim-node" codepath in + // ColladaLoader::StoreAnimations? For now, this has been deferred to after + // all animations and all clips have been read. Due to handling of + // this cannot be done here, as the channel owner + // is lost, and some exporters make up animations by referring to multiple + // single-channel animations from an . /* // special filtering for stupid exporters packing each channel into a separate animation if( channels.size() == 1) @@ -563,53 +710,53 @@ void ColladaParser::ReadAnimation( Collada::Animation* pParent) */ { // else create the animation, if not done yet, and store the channels - if( !anim) + if (!anim) { anim = new Animation; anim->mName = animName; - pParent->mSubAnims.push_back( anim); + pParent->mSubAnims.push_back(anim); } - for( ChannelMap::const_iterator it = channels.begin(); it != channels.end(); ++it) - anim->mChannels.push_back( it->second); + for (ChannelMap::const_iterator it = channels.begin(); it != channels.end(); ++it) + anim->mChannels.push_back(it->second); - if (indexID >= 0) - { - mAnimationLibrary[animID] = anim; - } + if (indexID >= 0) + { + mAnimationLibrary[animID] = anim; + } } } } // ------------------------------------------------------------------------------------------------ // Reads an animation sampler into the given anim channel -void ColladaParser::ReadAnimationSampler( Collada::AnimationChannel& pChannel) +void ColladaParser::ReadAnimationSampler(Collada::AnimationChannel& pChannel) { - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "input")) + if (IsElement("input")) { - int indexSemantic = GetAttribute( "semantic"); - const char* semantic = mReader->getAttributeValue( indexSemantic); - int indexSource = GetAttribute( "source"); - const char* source = mReader->getAttributeValue( indexSource); - if( source[0] != '#') - ThrowException( "Unsupported URL format"); + int indexSemantic = GetAttribute("semantic"); + const char* semantic = mReader->getAttributeValue(indexSemantic); + int indexSource = GetAttribute("source"); + const char* source = mReader->getAttributeValue(indexSource); + if (source[0] != '#') + ThrowException("Unsupported URL format"); source++; - if( strcmp( semantic, "INPUT") == 0) + if (strcmp(semantic, "INPUT") == 0) pChannel.mSourceTimes = source; - else if( strcmp( semantic, "OUTPUT") == 0) + else if (strcmp(semantic, "OUTPUT") == 0) pChannel.mSourceValues = source; - else if( strcmp( semantic, "IN_TANGENT") == 0) + else if (strcmp(semantic, "IN_TANGENT") == 0) pChannel.mInTanValues = source; - else if( strcmp( semantic, "OUT_TANGENT") == 0) + else if (strcmp(semantic, "OUT_TANGENT") == 0) pChannel.mOutTanValues = source; - else if( strcmp( semantic, "INTERPOLATION") == 0) + else if (strcmp(semantic, "INTERPOLATION") == 0) pChannel.mInterpolationValues = source; - if( !mReader->isEmptyElement()) + if (!mReader->isEmptyElement()) SkipElement(); } else @@ -618,10 +765,10 @@ void ColladaParser::ReadAnimationSampler( Collada::AnimationChannel& pChannel) SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "sampler") != 0) - ThrowException( "Expected end of element."); + if (strcmp(mReader->getNodeName(), "sampler") != 0) + ThrowException("Expected end of element."); break; } @@ -635,31 +782,32 @@ void ColladaParser::ReadControllerLibrary() if (mReader->isEmptyElement()) return; - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "controller")) + if (IsElement("controller")) { // read ID. Ask the spec if it's necessary or optional... you might be surprised. - int attrID = GetAttribute( "id"); - std::string id = mReader->getAttributeValue( attrID); + int attrID = GetAttribute("id"); + std::string id = mReader->getAttributeValue(attrID); // create an entry and store it in the library under its ID mControllerLibrary[id] = Controller(); // read on from there - ReadController( mControllerLibrary[id]); - } else + ReadController(mControllerLibrary[id]); + } + else { // ignore the rest SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "library_controllers") != 0) - ThrowException( "Expected end of element."); + if (strcmp(mReader->getNodeName(), "library_controllers") != 0) + ThrowException("Expected end of element."); break; } @@ -668,17 +816,17 @@ void ColladaParser::ReadControllerLibrary() // ------------------------------------------------------------------------------------------------ // 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) { // two types of controllers: "skin" and "morph". Only the first one is relevant, we skip the other - if( IsElement( "morph")) + if (IsElement("morph")) { pController.mType = Morph; int baseIndex = GetAttribute("source"); @@ -690,47 +838,47 @@ void ColladaParser::ReadController( Collada::Controller& pController) pController.mMethod = Relative; } } - else if( IsElement( "skin")) + else if (IsElement("skin")) { // read the mesh it refers to. According to the spec this could also be another // controller, but I refuse to implement every single idea they've come up with - int sourceIndex = GetAttribute( "source"); - pController.mMeshId = mReader->getAttributeValue( sourceIndex) + 1; + int sourceIndex = GetAttribute("source"); + pController.mMeshId = mReader->getAttributeValue(sourceIndex) + 1; } - 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 const char* content = GetTextContent(); // read the 16 floats - for( unsigned int a = 0; a < 16; a++) + for (unsigned int a = 0; a < 16; a++) { // read a number - content = fast_atoreal_move( content, pController.mBindShapeMatrix[a]); + content = fast_atoreal_move(content, pController.mBindShapeMatrix[a]); // skip whitespace after it - SkipSpacesAndLineEnd( &content); + SkipSpacesAndLineEnd(&content); } - TestClosing( "bind_shape_matrix"); + TestClosing("bind_shape_matrix"); } - else if( IsElement( "source")) + else if (IsElement("source")) { // data array - we have specialists to handle this ReadSource(); } - else if( IsElement( "joints")) + else if (IsElement("joints")) { - ReadControllerJoints( pController); + ReadControllerJoints(pController); } - else if( IsElement( "vertex_weights")) + else if (IsElement("vertex_weights")) { - ReadControllerWeights( pController); + ReadControllerWeights(pController); } - else if ( IsElement( "targets" )) + else if (IsElement("targets")) { while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if ( IsElement( "input")) { + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { + if (IsElement("input")) { int semanticsIndex = GetAttribute("semantic"); int sourceIndex = GetAttribute("source"); @@ -744,11 +892,12 @@ void ColladaParser::ReadController( Collada::Controller& pController) pController.mMorphWeight = source + 1; } } - } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "targets") == 0) + } + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { + if (strcmp(mReader->getNodeName(), "targets") == 0) break; else - ThrowException( "Expected end of element."); + ThrowException("Expected end of element."); } } } @@ -758,47 +907,47 @@ void ColladaParser::ReadController( Collada::Controller& pController) SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "controller") == 0) + if (strcmp(mReader->getNodeName(), "controller") == 0) break; - else if( strcmp( mReader->getNodeName(), "skin") != 0 && strcmp( mReader->getNodeName(), "morph") != 0) - ThrowException( "Expected end of element."); + else if (strcmp(mReader->getNodeName(), "skin") != 0 && strcmp(mReader->getNodeName(), "morph") != 0) + ThrowException("Expected end of element."); } } } // ------------------------------------------------------------------------------------------------ // Reads the joint definitions for the given controller -void ColladaParser::ReadControllerJoints( Collada::Controller& pController) +void ColladaParser::ReadControllerJoints(Collada::Controller& pController) { - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { // Input channels for joint data. Two possible semantics: "JOINT" and "INV_BIND_MATRIX" - if( IsElement( "input")) + if (IsElement("input")) { - int indexSemantic = GetAttribute( "semantic"); - const char* attrSemantic = mReader->getAttributeValue( indexSemantic); - int indexSource = GetAttribute( "source"); - const char* attrSource = mReader->getAttributeValue( indexSource); + int indexSemantic = GetAttribute("semantic"); + const char* attrSemantic = mReader->getAttributeValue(indexSemantic); + int indexSource = GetAttribute("source"); + const char* attrSource = mReader->getAttributeValue(indexSource); // local URLS always start with a '#'. We don't support global URLs - if( attrSource[0] != '#') - ThrowException( format() << "Unsupported URL format in \"" << attrSource << "\" in source attribute of data element" ); + if (attrSource[0] != '#') + ThrowException(format() << "Unsupported URL format in \"" << attrSource << "\" in source attribute of data element"); attrSource++; // parse source URL to corresponding source - if( strcmp( attrSemantic, "JOINT") == 0) + if (strcmp(attrSemantic, "JOINT") == 0) pController.mJointNameSource = attrSource; - else if( strcmp( attrSemantic, "INV_BIND_MATRIX") == 0) + else if (strcmp(attrSemantic, "INV_BIND_MATRIX") == 0) pController.mJointOffsetMatrixSource = attrSource; else - ThrowException( format() << "Unknown semantic \"" << attrSemantic << "\" in data element" ); + ThrowException(format() << "Unknown semantic \"" << attrSemantic << "\" in data element"); // skip inner data, if present - if( !mReader->isEmptyElement()) + if (!mReader->isEmptyElement()) SkipElement(); } else @@ -807,10 +956,10 @@ void ColladaParser::ReadControllerJoints( Collada::Controller& pController) SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "joints") != 0) - ThrowException( "Expected end of element."); + if (strcmp(mReader->getNodeName(), "joints") != 0) + ThrowException("Expected end of element."); break; } @@ -819,85 +968,85 @@ void ColladaParser::ReadControllerJoints( Collada::Controller& pController) // ------------------------------------------------------------------------------------------------ // Reads the joint weights for the given controller -void ColladaParser::ReadControllerWeights( Collada::Controller& pController) +void ColladaParser::ReadControllerWeights(Collada::Controller& pController) { // read vertex count from attributes and resize the array accordingly - int indexCount = GetAttribute( "count"); - size_t vertexCount = (size_t) mReader->getAttributeValueAsInt( indexCount); - pController.mWeightCounts.resize( vertexCount); + int indexCount = GetAttribute("count"); + size_t vertexCount = (size_t)mReader->getAttributeValueAsInt(indexCount); + pController.mWeightCounts.resize(vertexCount); - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { // Input channels for weight data. Two possible semantics: "JOINT" and "WEIGHT" - if( IsElement( "input") && vertexCount > 0 ) + if (IsElement("input") && vertexCount > 0) { InputChannel channel; - int indexSemantic = GetAttribute( "semantic"); - const char* attrSemantic = mReader->getAttributeValue( indexSemantic); - int indexSource = GetAttribute( "source"); - const char* attrSource = mReader->getAttributeValue( indexSource); - int indexOffset = TestAttribute( "offset"); - if( indexOffset >= 0) - channel.mOffset = mReader->getAttributeValueAsInt( indexOffset); + int indexSemantic = GetAttribute("semantic"); + const char* attrSemantic = mReader->getAttributeValue(indexSemantic); + int indexSource = GetAttribute("source"); + const char* attrSource = mReader->getAttributeValue(indexSource); + int indexOffset = TestAttribute("offset"); + if (indexOffset >= 0) + channel.mOffset = mReader->getAttributeValueAsInt(indexOffset); // local URLS always start with a '#'. We don't support global URLs - if( attrSource[0] != '#') - ThrowException( format() << "Unsupported URL format in \"" << attrSource << "\" in source attribute of data element" ); + if (attrSource[0] != '#') + ThrowException(format() << "Unsupported URL format in \"" << attrSource << "\" in source attribute of data element"); channel.mAccessor = attrSource + 1; // parse source URL to corresponding source - if( strcmp( attrSemantic, "JOINT") == 0) + if (strcmp(attrSemantic, "JOINT") == 0) pController.mWeightInputJoints = channel; - else if( strcmp( attrSemantic, "WEIGHT") == 0) + else if (strcmp(attrSemantic, "WEIGHT") == 0) pController.mWeightInputWeights = channel; else - ThrowException( format() << "Unknown semantic \"" << attrSemantic << "\" in data element" ); + ThrowException(format() << "Unknown semantic \"" << attrSemantic << "\" in data element"); // skip inner data, if present - if( !mReader->isEmptyElement()) + if (!mReader->isEmptyElement()) SkipElement(); } - else if( IsElement( "vcount") && vertexCount > 0 ) + else if (IsElement("vcount") && vertexCount > 0) { // read weight count per vertex const char* text = GetTextContent(); size_t numWeights = 0; - for( std::vector::iterator it = pController.mWeightCounts.begin(); it != pController.mWeightCounts.end(); ++it) + for (std::vector::iterator it = pController.mWeightCounts.begin(); it != pController.mWeightCounts.end(); ++it) { - if( *text == 0) - ThrowException( "Out of data while reading "); + if (*text == 0) + ThrowException("Out of data while reading "); - *it = strtoul10( text, &text); + *it = strtoul10(text, &text); numWeights += *it; - SkipSpacesAndLineEnd( &text); + SkipSpacesAndLineEnd(&text); } - TestClosing( "vcount"); + TestClosing("vcount"); // reserve weight count - pController.mWeights.resize( numWeights); + pController.mWeights.resize(numWeights); } - else if( IsElement( "v") && vertexCount > 0 ) + else if (IsElement("v") && vertexCount > 0) { // read JointIndex - WeightIndex pairs const char* text = GetTextContent(); - for( std::vector< std::pair >::iterator it = pController.mWeights.begin(); it != pController.mWeights.end(); ++it) + for (std::vector< std::pair >::iterator it = pController.mWeights.begin(); it != pController.mWeights.end(); ++it) { - if( *text == 0) - ThrowException( "Out of data while reading "); - it->first = strtoul10( text, &text); - SkipSpacesAndLineEnd( &text); - if( *text == 0) - ThrowException( "Out of data while reading "); - it->second = strtoul10( text, &text); - SkipSpacesAndLineEnd( &text); + if (*text == 0) + ThrowException("Out of data while reading "); + it->first = strtoul10(text, &text); + SkipSpacesAndLineEnd(&text); + if (*text == 0) + ThrowException("Out of data while reading "); + it->second = strtoul10(text, &text); + SkipSpacesAndLineEnd(&text); } - TestClosing( "v"); + TestClosing("v"); } else { @@ -905,10 +1054,10 @@ void ColladaParser::ReadControllerWeights( Collada::Controller& pController) SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "vertex_weights") != 0) - ThrowException( "Expected end of element."); + if (strcmp(mReader->getNodeName(), "vertex_weights") != 0) + ThrowException("Expected end of element."); break; } @@ -919,32 +1068,33 @@ void ColladaParser::ReadControllerWeights( Collada::Controller& pController) // Reads the image library contents void ColladaParser::ReadImageLibrary() { - if( mReader->isEmptyElement()) + if (mReader->isEmptyElement()) return; - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "image")) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { + if (IsElement("image")) { // read ID. Another entry which is "optional" by design but obligatory in reality - int attrID = GetAttribute( "id"); - std::string id = mReader->getAttributeValue( attrID); + int attrID = GetAttribute("id"); + std::string id = mReader->getAttributeValue(attrID); // create an entry and store it in the library under its ID mImageLibrary[id] = Image(); // read on from there - ReadImage( mImageLibrary[id]); - } else + ReadImage(mImageLibrary[id]); + } + else { // ignore the rest SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "library_images") != 0) - ThrowException( "Expected end of element."); + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { + if (strcmp(mReader->getNodeName(), "library_images") != 0) + ThrowException("Expected end of element."); break; } @@ -953,16 +1103,16 @@ void ColladaParser::ReadImageLibrary() // ------------------------------------------------------------------------------------------------ // Reads an image entry into the given image -void ColladaParser::ReadImage( Collada::Image& pImage) +void ColladaParser::ReadImage(Collada::Image& pImage) { - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT){ + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { // Need to run different code paths here, depending on the Collada XSD version if (IsElement("image")) { SkipElement(); } - else if( IsElement( "init_from")) + else if (IsElement("init_from")) { if (mFormat == FV_1_4_n) { @@ -971,7 +1121,7 @@ void ColladaParser::ReadImage( Collada::Image& pImage) // element content is filename - hopefully const char* sz = TestTextContent(); if (sz)pImage.mFileName = sz; - TestClosing( "init_from"); + TestClosing("init_from"); } if (!pImage.mFileName.length()) { pImage.mFileName = "unknown_texture"; @@ -999,14 +1149,14 @@ void ColladaParser::ReadImage( Collada::Image& pImage) } else if (mFormat == FV_1_5_n) { - if( IsElement( "ref")) + if (IsElement("ref")) { // element content is filename - hopefully const char* sz = TestTextContent(); if (sz)pImage.mFileName = sz; - TestClosing( "ref"); + TestClosing("ref"); } - else if( IsElement( "hex") && !pImage.mFileName.length()) + else if (IsElement("hex") && !pImage.mFileName.length()) { // embedded image. get format const int attrib = TestAttribute("format"); @@ -1021,12 +1171,12 @@ void ColladaParser::ReadImage( Collada::Image& pImage) const char* cur = data; while (!IsSpaceOrNewLine(*cur)) cur++; - const unsigned int size = (unsigned int)(cur-data) * 2; + const unsigned int size = (unsigned int)(cur - data) * 2; pImage.mImageData.resize(size); - for (unsigned int i = 0; i < size;++i) - pImage.mImageData[i] = HexOctetToDecimal(data+(i<<1)); + for (unsigned int i = 0; i < size; ++i) + pImage.mImageData[i] = HexOctetToDecimal(data + (i << 1)); - TestClosing( "hex"); + TestClosing("hex"); } } else @@ -1035,8 +1185,8 @@ void ColladaParser::ReadImage( Collada::Image& pImage) SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "image") == 0) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { + if (strcmp(mReader->getNodeName(), "image") == 0) break; } } @@ -1046,36 +1196,36 @@ void ColladaParser::ReadImage( Collada::Image& pImage) // Reads the material library void ColladaParser::ReadMaterialLibrary() { - if( mReader->isEmptyElement()) + if (mReader->isEmptyElement()) return; std::map names; - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "material")) + if (IsElement("material")) { // read ID. By now you probably know my opinion about this "specification" - int attrID = GetAttribute( "id"); - std::string id = mReader->getAttributeValue( attrID); + int attrID = GetAttribute("id"); + std::string id = mReader->getAttributeValue(attrID); std::string name; int attrName = TestAttribute("name"); if (attrName >= 0) - name = mReader->getAttributeValue( attrName); + name = mReader->getAttributeValue(attrName); // create an entry and store it in the library under its ID mMaterialLibrary[id] = Material(); - if( !name.empty()) + if (!name.empty()) { - std::map::iterator it = names.find( name); - if( it != names.end()) + std::map::iterator it = names.find(name); + if (it != names.end()) { std::ostringstream strStream; strStream << ++it->second; - name.append( " " + strStream.str()); + name.append(" " + strStream.str()); } else { @@ -1085,17 +1235,18 @@ void ColladaParser::ReadMaterialLibrary() mMaterialLibrary[id].mName = name; } - ReadMaterial( mMaterialLibrary[id]); - } else + ReadMaterial(mMaterialLibrary[id]); + } + else { // ignore the rest SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "library_materials") != 0) - ThrowException( "Expected end of element."); + if (strcmp(mReader->getNodeName(), "library_materials") != 0) + ThrowException("Expected end of element."); break; } @@ -1106,30 +1257,31 @@ void ColladaParser::ReadMaterialLibrary() // Reads the light library void ColladaParser::ReadLightLibrary() { - if( mReader->isEmptyElement()) + if (mReader->isEmptyElement()) return; - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "light")) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { + if (IsElement("light")) { // read ID. By now you probably know my opinion about this "specification" - int attrID = GetAttribute( "id"); - std::string id = mReader->getAttributeValue( attrID); + int attrID = GetAttribute("id"); + std::string id = mReader->getAttributeValue(attrID); // create an entry and store it in the library under its ID ReadLight(mLightLibrary[id] = Light()); - } else + } + else { // ignore the rest SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "library_lights") != 0) - ThrowException( "Expected end of element."); + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { + if (strcmp(mReader->getNodeName(), "library_lights") != 0) + ThrowException("Expected end of element."); break; } @@ -1140,35 +1292,36 @@ void ColladaParser::ReadLightLibrary() // Reads the camera library void ColladaParser::ReadCameraLibrary() { - if( mReader->isEmptyElement()) + if (mReader->isEmptyElement()) return; - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "camera")) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { + if (IsElement("camera")) { // read ID. By now you probably know my opinion about this "specification" - int attrID = GetAttribute( "id"); - std::string id = mReader->getAttributeValue( attrID); + int attrID = GetAttribute("id"); + std::string id = mReader->getAttributeValue(attrID); // create an entry and store it in the library under its ID Camera& cam = mCameraLibrary[id]; - attrID = TestAttribute( "name"); + attrID = TestAttribute("name"); if (attrID != -1) - cam.mName = mReader->getAttributeValue( attrID); + cam.mName = mReader->getAttributeValue(attrID); ReadCamera(cam); - } else + } + else { // ignore the rest SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "library_cameras") != 0) - ThrowException( "Expected end of element."); + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { + if (strcmp(mReader->getNodeName(), "library_cameras") != 0) + ThrowException("Expected end of element."); break; } @@ -1177,34 +1330,35 @@ void ColladaParser::ReadCameraLibrary() // ------------------------------------------------------------------------------------------------ // Reads a material entry into the given material -void ColladaParser::ReadMaterial( Collada::Material& pMaterial) +void ColladaParser::ReadMaterial(Collada::Material& pMaterial) { - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { if (IsElement("material")) { SkipElement(); } - else if( IsElement( "instance_effect")) + else if (IsElement("instance_effect")) { // referred effect by URL - int attrUrl = GetAttribute( "url"); - const char* url = mReader->getAttributeValue( attrUrl); - if( url[0] != '#') - ThrowException( "Unknown reference format"); + int attrUrl = GetAttribute("url"); + const char* url = mReader->getAttributeValue(attrUrl); + if (url[0] != '#') + ThrowException("Unknown reference format"); - pMaterial.mEffect = url+1; + pMaterial.mEffect = url + 1; SkipElement(); - } else + } + else { // ignore the rest SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "material") != 0) - ThrowException( "Expected end of element."); + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { + if (strcmp(mReader->getNodeName(), "material") != 0) + ThrowException("Expected end of element."); break; } @@ -1213,11 +1367,11 @@ void ColladaParser::ReadMaterial( Collada::Material& pMaterial) // ------------------------------------------------------------------------------------------------ // Reads a light entry into the given light -void ColladaParser::ReadLight( Collada::Light& pLight) +void ColladaParser::ReadLight(Collada::Light& pLight) { - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { if (IsElement("light")) { SkipElement(); } @@ -1237,16 +1391,16 @@ void ColladaParser::ReadLight( Collada::Light& pLight) // text content contains 3 floats const char* content = GetTextContent(); - content = fast_atoreal_move( content, (ai_real&)pLight.mColor.r); - SkipSpacesAndLineEnd( &content); + content = fast_atoreal_move(content, (ai_real&)pLight.mColor.r); + SkipSpacesAndLineEnd(&content); - content = fast_atoreal_move( content, (ai_real&)pLight.mColor.g); - SkipSpacesAndLineEnd( &content); + content = fast_atoreal_move(content, (ai_real&)pLight.mColor.g); + SkipSpacesAndLineEnd(&content); - content = fast_atoreal_move( content, (ai_real&)pLight.mColor.b); - SkipSpacesAndLineEnd( &content); + content = fast_atoreal_move(content, (ai_real&)pLight.mColor.b); + SkipSpacesAndLineEnd(&content); - TestClosing( "color"); + TestClosing("color"); } else if (IsElement("constant_attenuation")) { pLight.mAttConstant = ReadFloatFromTextContent(); @@ -1298,8 +1452,8 @@ void ColladaParser::ReadLight( Collada::Light& pLight) TestClosing("decay_falloff"); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "light") == 0) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { + if (strcmp(mReader->getNodeName(), "light") == 0) break; } } @@ -1307,11 +1461,11 @@ void ColladaParser::ReadLight( Collada::Light& pLight) // ------------------------------------------------------------------------------------------------ // Reads a camera entry into the given light -void ColladaParser::ReadCamera( Collada::Camera& pCamera) +void ColladaParser::ReadCamera(Collada::Camera& pCamera) { - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { if (IsElement("camera")) { SkipElement(); } @@ -1339,8 +1493,8 @@ void ColladaParser::ReadCamera( Collada::Camera& pCamera) TestClosing("zfar"); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "camera") == 0) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { + if (strcmp(mReader->getNodeName(), "camera") == 0) break; } } @@ -1354,28 +1508,29 @@ void ColladaParser::ReadEffectLibrary() return; } - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "effect")) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { + if (IsElement("effect")) { // read ID. Do I have to repeat my ranting about "optional" attributes? - int attrID = GetAttribute( "id"); - std::string id = mReader->getAttributeValue( attrID); + int attrID = GetAttribute("id"); + std::string id = mReader->getAttributeValue(attrID); // create an entry and store it in the library under its ID mEffectLibrary[id] = Effect(); // read on from there - ReadEffect( mEffectLibrary[id]); - } else + ReadEffect(mEffectLibrary[id]); + } + else { // ignore the rest SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "library_effects") != 0) - ThrowException( "Expected end of element."); + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { + if (strcmp(mReader->getNodeName(), "library_effects") != 0) + ThrowException("Expected end of element."); break; } @@ -1384,22 +1539,22 @@ void ColladaParser::ReadEffectLibrary() // ------------------------------------------------------------------------------------------------ // Reads an effect entry into the given effect -void ColladaParser::ReadEffect( Collada::Effect& pEffect) +void ColladaParser::ReadEffect(Collada::Effect& pEffect) { // for the moment we don't support any other type of effect. - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "profile_COMMON")) - ReadEffectProfileCommon( pEffect); + if (IsElement("profile_COMMON")) + ReadEffectProfileCommon(pEffect); else SkipElement(); } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "effect") != 0) - ThrowException( "Expected end of element."); + if (strcmp(mReader->getNodeName(), "effect") != 0) + ThrowException("Expected end of element."); break; } @@ -1408,107 +1563,107 @@ void ColladaParser::ReadEffect( Collada::Effect& pEffect) // ------------------------------------------------------------------------------------------------ // Reads an COMMON effect profile -void ColladaParser::ReadEffectProfileCommon( Collada::Effect& pEffect) +void ColladaParser::ReadEffectProfileCommon(Collada::Effect& pEffect) { - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "newparam")) { + if (IsElement("newparam")) { // save ID - int attrSID = GetAttribute( "sid"); - std::string sid = mReader->getAttributeValue( attrSID); + int attrSID = GetAttribute("sid"); + std::string sid = mReader->getAttributeValue(attrSID); pEffect.mParams[sid] = EffectParam(); - ReadEffectParam( pEffect.mParams[sid]); + ReadEffectParam(pEffect.mParams[sid]); } - else if( IsElement( "technique") || IsElement( "extra")) + else if (IsElement("technique") || IsElement("extra")) { // just syntactic sugar } - else if( mFormat == FV_1_4_n && IsElement( "image")) + else if (mFormat == FV_1_4_n && IsElement("image")) { // read ID. Another entry which is "optional" by design but obligatory in reality - int attrID = GetAttribute( "id"); - std::string id = mReader->getAttributeValue( attrID); + int attrID = GetAttribute("id"); + std::string id = mReader->getAttributeValue(attrID); // create an entry and store it in the library under its ID mImageLibrary[id] = Image(); // read on from there - ReadImage( mImageLibrary[id]); + ReadImage(mImageLibrary[id]); } /* Shading modes */ - else if( IsElement( "phong")) + else if (IsElement("phong")) pEffect.mShadeType = Shade_Phong; - else if( IsElement( "constant")) + else if (IsElement("constant")) pEffect.mShadeType = Shade_Constant; - else if( IsElement( "lambert")) + else if (IsElement("lambert")) pEffect.mShadeType = Shade_Lambert; - else if( IsElement( "blinn")) + else if (IsElement("blinn")) pEffect.mShadeType = Shade_Blinn; /* Color + texture properties */ - else if( IsElement( "emission")) - ReadEffectColor( pEffect.mEmissive, pEffect.mTexEmissive); - else if( IsElement( "ambient")) - ReadEffectColor( pEffect.mAmbient, pEffect.mTexAmbient); - else if( IsElement( "diffuse")) - ReadEffectColor( pEffect.mDiffuse, pEffect.mTexDiffuse); - else if( IsElement( "specular")) - ReadEffectColor( pEffect.mSpecular, pEffect.mTexSpecular); - else if( IsElement( "reflective")) { - ReadEffectColor( pEffect.mReflective, pEffect.mTexReflective); + else if (IsElement("emission")) + ReadEffectColor(pEffect.mEmissive, pEffect.mTexEmissive); + else if (IsElement("ambient")) + ReadEffectColor(pEffect.mAmbient, pEffect.mTexAmbient); + else if (IsElement("diffuse")) + ReadEffectColor(pEffect.mDiffuse, pEffect.mTexDiffuse); + else if (IsElement("specular")) + ReadEffectColor(pEffect.mSpecular, pEffect.mTexSpecular); + else if (IsElement("reflective")) { + ReadEffectColor(pEffect.mReflective, pEffect.mTexReflective); } - else if( IsElement( "transparent")) { + else if (IsElement("transparent")) { pEffect.mHasTransparency = true; const char* opaque = mReader->getAttributeValueSafe("opaque"); - if(::strcmp(opaque, "RGB_ZERO") == 0 || ::strcmp(opaque, "RGB_ONE") == 0) { + if (::strcmp(opaque, "RGB_ZERO") == 0 || ::strcmp(opaque, "RGB_ONE") == 0) { pEffect.mRGBTransparency = true; } // In RGB_ZERO mode, the transparency is interpreted in reverse, go figure... - if(::strcmp(opaque, "RGB_ZERO") == 0 || ::strcmp(opaque, "A_ZERO") == 0) { - pEffect.mInvertTransparency = true; - } + if (::strcmp(opaque, "RGB_ZERO") == 0 || ::strcmp(opaque, "A_ZERO") == 0) { + pEffect.mInvertTransparency = true; + } - ReadEffectColor( pEffect.mTransparent,pEffect.mTexTransparent); + ReadEffectColor(pEffect.mTransparent, pEffect.mTexTransparent); } - else if( IsElement( "shininess")) - ReadEffectFloat( pEffect.mShininess); - else if( IsElement( "reflectivity")) - ReadEffectFloat( pEffect.mReflectivity); + else if (IsElement("shininess")) + ReadEffectFloat(pEffect.mShininess); + else if (IsElement("reflectivity")) + ReadEffectFloat(pEffect.mReflectivity); /* Single scalar properties */ - else if( IsElement( "transparency")) - ReadEffectFloat( pEffect.mTransparency); - else if( IsElement( "index_of_refraction")) - ReadEffectFloat( pEffect.mRefractIndex); + else if (IsElement("transparency")) + ReadEffectFloat(pEffect.mTransparency); + else if (IsElement("index_of_refraction")) + ReadEffectFloat(pEffect.mRefractIndex); // GOOGLEEARTH/OKINO extensions // ------------------------------------------------------- - else if( IsElement( "double_sided")) + else if (IsElement("double_sided")) pEffect.mDoubleSided = ReadBoolFromTextContent(); // FCOLLADA extensions // ------------------------------------------------------- - else if( IsElement( "bump")) { + else if (IsElement("bump")) { aiColor4D dummy; - ReadEffectColor( dummy,pEffect.mTexBump); + ReadEffectColor(dummy, pEffect.mTexBump); } // MAX3D extensions // ------------------------------------------------------- - else if( IsElement( "wireframe")) { + else if (IsElement("wireframe")) { pEffect.mWireframe = ReadBoolFromTextContent(); - TestClosing( "wireframe"); + TestClosing("wireframe"); } - else if( IsElement( "faceted")) { + else if (IsElement("faceted")) { pEffect.mFaceted = ReadBoolFromTextContent(); - TestClosing( "faceted"); + TestClosing("faceted"); } else { @@ -1516,8 +1671,8 @@ void ColladaParser::ReadEffectProfileCommon( Collada::Effect& pEffect) SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "profile_COMMON") == 0) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { + if (strcmp(mReader->getNodeName(), "profile_COMMON") == 0) { break; } @@ -1527,92 +1682,92 @@ void ColladaParser::ReadEffectProfileCommon( Collada::Effect& pEffect) // ------------------------------------------------------------------------------------------------ // Read texture wrapping + UV transform settings from a profile==Maya chunk -void ColladaParser::ReadSamplerProperties( Sampler& out ) +void ColladaParser::ReadSamplerProperties(Sampler& out) { if (mReader->isEmptyElement()) { return; } - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { // MAYA extensions // ------------------------------------------------------- - if( IsElement( "wrapU")) { + if (IsElement("wrapU")) { out.mWrapU = ReadBoolFromTextContent(); - TestClosing( "wrapU"); + TestClosing("wrapU"); } - else if( IsElement( "wrapV")) { + else if (IsElement("wrapV")) { out.mWrapV = ReadBoolFromTextContent(); - TestClosing( "wrapV"); + TestClosing("wrapV"); } - else if( IsElement( "mirrorU")) { + else if (IsElement("mirrorU")) { out.mMirrorU = ReadBoolFromTextContent(); - TestClosing( "mirrorU"); + TestClosing("mirrorU"); } - else if( IsElement( "mirrorV")) { + else if (IsElement("mirrorV")) { out.mMirrorV = ReadBoolFromTextContent(); - TestClosing( "mirrorV"); + TestClosing("mirrorV"); } - else if( IsElement( "repeatU")) { + else if (IsElement("repeatU")) { out.mTransform.mScaling.x = ReadFloatFromTextContent(); - TestClosing( "repeatU"); + TestClosing("repeatU"); } - else if( IsElement( "repeatV")) { + else if (IsElement("repeatV")) { out.mTransform.mScaling.y = ReadFloatFromTextContent(); - TestClosing( "repeatV"); + TestClosing("repeatV"); } - else if( IsElement( "offsetU")) { + else if (IsElement("offsetU")) { out.mTransform.mTranslation.x = ReadFloatFromTextContent(); - TestClosing( "offsetU"); + TestClosing("offsetU"); } - else if( IsElement( "offsetV")) { + else if (IsElement("offsetV")) { out.mTransform.mTranslation.y = ReadFloatFromTextContent(); - TestClosing( "offsetV"); + TestClosing("offsetV"); } - else if( IsElement( "rotateUV")) { + else if (IsElement("rotateUV")) { out.mTransform.mRotation = ReadFloatFromTextContent(); - TestClosing( "rotateUV"); + TestClosing("rotateUV"); } - else if( IsElement( "blend_mode")) { + else if (IsElement("blend_mode")) { const char* sz = GetTextContent(); // http://www.feelingsoftware.com/content/view/55/72/lang,en/ // NONE, OVER, IN, OUT, ADD, SUBTRACT, MULTIPLY, DIFFERENCE, LIGHTEN, DARKEN, SATURATE, DESATURATE and ILLUMINATE - if (0 == ASSIMP_strincmp(sz,"ADD",3)) + if (0 == ASSIMP_strincmp(sz, "ADD", 3)) out.mOp = aiTextureOp_Add; - else if (0 == ASSIMP_strincmp(sz,"SUBTRACT",8)) + else if (0 == ASSIMP_strincmp(sz, "SUBTRACT", 8)) out.mOp = aiTextureOp_Subtract; - else if (0 == ASSIMP_strincmp(sz,"MULTIPLY",8)) + else if (0 == ASSIMP_strincmp(sz, "MULTIPLY", 8)) out.mOp = aiTextureOp_Multiply; - else { + else { ASSIMP_LOG_WARN("Collada: Unsupported MAYA texture blend mode"); } - TestClosing( "blend_mode"); + TestClosing("blend_mode"); } // OKINO extensions // ------------------------------------------------------- - else if( IsElement( "weighting")) { + else if (IsElement("weighting")) { out.mWeighting = ReadFloatFromTextContent(); - TestClosing( "weighting"); + TestClosing("weighting"); } - else if( IsElement( "mix_with_previous_layer")) { + else if (IsElement("mix_with_previous_layer")) { out.mMixWithPrevious = ReadFloatFromTextContent(); - TestClosing( "mix_with_previous_layer"); + TestClosing("mix_with_previous_layer"); } // MAX3D extensions // ------------------------------------------------------- - else if( IsElement( "amount")) { + else if (IsElement("amount")) { out.mWeighting = ReadFloatFromTextContent(); - TestClosing( "amount"); + TestClosing("amount"); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "technique") == 0) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { + if (strcmp(mReader->getNodeName(), "technique") == 0) break; } } @@ -1620,7 +1775,7 @@ void ColladaParser::ReadSamplerProperties( Sampler& out ) // ------------------------------------------------------------------------------------------------ // Reads an effect entry containing a color or a texture defining that color -void ColladaParser::ReadEffectColor( aiColor4D& pColor, Sampler& pSampler) +void ColladaParser::ReadEffectColor(aiColor4D& pColor, Sampler& pSampler) { if (mReader->isEmptyElement()) return; @@ -1628,64 +1783,64 @@ void ColladaParser::ReadEffectColor( aiColor4D& pColor, Sampler& pSampler) // Save current element name const std::string curElem = mReader->getNodeName(); - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "color")) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { + if (IsElement("color")) { // text content contains 4 floats const char* content = GetTextContent(); - content = fast_atoreal_move( content, (ai_real&)pColor.r); - SkipSpacesAndLineEnd( &content); + content = fast_atoreal_move(content, (ai_real&)pColor.r); + SkipSpacesAndLineEnd(&content); - content = fast_atoreal_move( content, (ai_real&)pColor.g); - SkipSpacesAndLineEnd( &content); + content = fast_atoreal_move(content, (ai_real&)pColor.g); + SkipSpacesAndLineEnd(&content); - content = fast_atoreal_move( content, (ai_real&)pColor.b); - SkipSpacesAndLineEnd( &content); + content = fast_atoreal_move(content, (ai_real&)pColor.b); + SkipSpacesAndLineEnd(&content); - content = fast_atoreal_move( content, (ai_real&)pColor.a); - SkipSpacesAndLineEnd( &content); - TestClosing( "color"); + content = fast_atoreal_move(content, (ai_real&)pColor.a); + SkipSpacesAndLineEnd(&content); + TestClosing("color"); } - else if( IsElement( "texture")) + else if (IsElement("texture")) { // get name of source texture/sampler - int attrTex = GetAttribute( "texture"); - pSampler.mName = mReader->getAttributeValue( attrTex); + int attrTex = GetAttribute("texture"); + pSampler.mName = mReader->getAttributeValue(attrTex); // get name of UV source channel. Specification demands it to be there, but some exporters // don't write it. It will be the default UV channel in case it's missing. - attrTex = TestAttribute( "texcoord"); - if( attrTex >= 0 ) - pSampler.mUVChannel = mReader->getAttributeValue( attrTex); + attrTex = TestAttribute("texcoord"); + if (attrTex >= 0) + pSampler.mUVChannel = mReader->getAttributeValue(attrTex); //SkipElement(); // as we've read texture, the color needs to be 1,1,1,1 pColor = aiColor4D(1.f, 1.f, 1.f, 1.f); } - else if( IsElement( "technique")) + else if (IsElement("technique")) { - const int _profile = GetAttribute( "profile"); - const char* profile = mReader->getAttributeValue( _profile ); + const int _profile = GetAttribute("profile"); + const char* profile = mReader->getAttributeValue(_profile); // Some extensions are quite useful ... ReadSamplerProperties processes // several extensions in MAYA, OKINO and MAX3D profiles. - if (!::strcmp(profile,"MAYA") || !::strcmp(profile,"MAX3D") || !::strcmp(profile,"OKINO")) + if (!::strcmp(profile, "MAYA") || !::strcmp(profile, "MAX3D") || !::strcmp(profile, "OKINO")) { // get more information on this sampler ReadSamplerProperties(pSampler); } else SkipElement(); } - else if( !IsElement( "extra")) + else if (!IsElement("extra")) { // ignore the rest SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END){ + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if (mReader->getNodeName() == curElem) break; } @@ -1694,26 +1849,27 @@ void ColladaParser::ReadEffectColor( aiColor4D& pColor, Sampler& pSampler) // ------------------------------------------------------------------------------------------------ // Reads an effect entry containing a float -void ColladaParser::ReadEffectFloat( ai_real& pFloat) +void ColladaParser::ReadEffectFloat(ai_real& pFloat) { - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT){ - if( IsElement( "float")) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { + if (IsElement("float")) { // text content contains a single floats const char* content = GetTextContent(); - content = fast_atoreal_move( content, pFloat); - SkipSpacesAndLineEnd( &content); + content = fast_atoreal_move(content, pFloat); + SkipSpacesAndLineEnd(&content); - TestClosing( "float"); - } else + TestClosing("float"); + } + else { // ignore the rest SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END){ + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { break; } } @@ -1721,54 +1877,55 @@ void ColladaParser::ReadEffectFloat( ai_real& pFloat) // ------------------------------------------------------------------------------------------------ // Reads an effect parameter specification of any kind -void ColladaParser::ReadEffectParam( Collada::EffectParam& pParam) +void ColladaParser::ReadEffectParam(Collada::EffectParam& pParam) { - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "surface")) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { + if (IsElement("surface")) { // image ID given inside tags - TestOpening( "init_from"); + TestOpening("init_from"); const char* content = GetTextContent(); pParam.mType = Param_Surface; pParam.mReference = content; - TestClosing( "init_from"); + TestClosing("init_from"); // don't care for remaining stuff - SkipElement( "surface"); + SkipElement("surface"); } - else if( IsElement( "sampler2D") && (FV_1_4_n == mFormat || FV_1_3_n == mFormat)) + else if (IsElement("sampler2D") && (FV_1_4_n == mFormat || FV_1_3_n == mFormat)) { // surface ID is given inside tags - TestOpening( "source"); + TestOpening("source"); const char* content = GetTextContent(); pParam.mType = Param_Sampler; pParam.mReference = content; - TestClosing( "source"); + TestClosing("source"); // don't care for remaining stuff - SkipElement( "sampler2D"); + SkipElement("sampler2D"); } - else if( IsElement( "sampler2D")) + else if (IsElement("sampler2D")) { // surface ID is given inside tags - TestOpening( "instance_image"); + TestOpening("instance_image"); int attrURL = GetAttribute("url"); - const char* url = mReader->getAttributeValue( attrURL); - if( url[0] != '#') - ThrowException( "Unsupported URL format in instance_image"); + const char* url = mReader->getAttributeValue(attrURL); + if (url[0] != '#') + ThrowException("Unsupported URL format in instance_image"); url++; pParam.mType = Param_Sampler; pParam.mReference = url; - SkipElement( "sampler2D"); - } else + SkipElement("sampler2D"); + } + else { // ignore unknown element SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { break; } } @@ -1778,18 +1935,18 @@ void ColladaParser::ReadEffectParam( Collada::EffectParam& pParam) // Reads the geometry library contents void ColladaParser::ReadGeometryLibrary() { - if( mReader->isEmptyElement()) + if (mReader->isEmptyElement()) return; - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "geometry")) + if (IsElement("geometry")) { // read ID. Another entry which is "optional" by design but obligatory in reality - int indexID = GetAttribute( "id"); - std::string id = mReader->getAttributeValue( indexID); + int indexID = GetAttribute("id"); + std::string id = mReader->getAttributeValue(indexID); // TODO: (thom) support SIDs // ai_assert( TestAttribute( "sid") == -1); @@ -1800,23 +1957,24 @@ void ColladaParser::ReadGeometryLibrary() // read the mesh name if it exists const int nameIndex = TestAttribute("name"); - if(nameIndex != -1) + if (nameIndex != -1) { mesh->mName = mReader->getAttributeValue(nameIndex); } // read on from there - ReadGeometry( mesh); - } else + ReadGeometry(mesh); + } + else { // ignore the rest SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "library_geometries") != 0) - ThrowException( "Expected end of element."); + if (strcmp(mReader->getNodeName(), "library_geometries") != 0) + ThrowException("Expected end of element."); break; } @@ -1825,29 +1983,30 @@ void ColladaParser::ReadGeometryLibrary() // ------------------------------------------------------------------------------------------------ // Reads a geometry from the geometry library. -void ColladaParser::ReadGeometry( Collada::Mesh* pMesh) +void ColladaParser::ReadGeometry(Collada::Mesh* pMesh) { - if( mReader->isEmptyElement()) + if (mReader->isEmptyElement()) return; - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "mesh")) + if (IsElement("mesh")) { // read on from there - ReadMesh( pMesh); - } else + ReadMesh(pMesh); + } + else { // ignore the rest SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "geometry") != 0) - ThrowException( "Expected end of element."); + if (strcmp(mReader->getNodeName(), "geometry") != 0) + ThrowException("Expected end of element."); break; } @@ -1856,50 +2015,52 @@ void ColladaParser::ReadGeometry( Collada::Mesh* pMesh) // ------------------------------------------------------------------------------------------------ // Reads a mesh from the geometry library -void ColladaParser::ReadMesh( Mesh* pMesh) +void ColladaParser::ReadMesh(Mesh* pMesh) { - if( mReader->isEmptyElement()) + if (mReader->isEmptyElement()) return; - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "source")) + if (IsElement("source")) { // we have professionals dealing with this ReadSource(); } - else if( IsElement( "vertices")) + else if (IsElement("vertices")) { // read per-vertex mesh data - ReadVertexData( pMesh); + ReadVertexData(pMesh); } - else if( IsElement( "triangles") || IsElement( "lines") || IsElement( "linestrips") - || IsElement( "polygons") || IsElement( "polylist") || IsElement( "trifans") || IsElement( "tristrips")) + else if (IsElement("triangles") || IsElement("lines") || IsElement("linestrips") + || IsElement("polygons") || IsElement("polylist") || IsElement("trifans") || IsElement("tristrips")) { // read per-index mesh data and faces setup - ReadIndexData( pMesh); - } else + ReadIndexData(pMesh); + } + else { // ignore the restf SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "technique_common") == 0) + if (strcmp(mReader->getNodeName(), "technique_common") == 0) { // end of another meaningless element - read over it } - else if( strcmp( mReader->getNodeName(), "mesh") == 0) + else if (strcmp(mReader->getNodeName(), "mesh") == 0) { // end of element - we're done here break; - } else + } + else { // everything else should be punished - ThrowException( "Expected end of element."); + ThrowException("Expected end of element."); } } } @@ -1909,44 +2070,46 @@ void ColladaParser::ReadMesh( Mesh* pMesh) // Reads a source element void ColladaParser::ReadSource() { - int indexID = GetAttribute( "id"); - std::string sourceID = mReader->getAttributeValue( indexID); + int indexID = GetAttribute("id"); + std::string sourceID = mReader->getAttributeValue(indexID); - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "float_array") || IsElement( "IDREF_array") || IsElement( "Name_array")) + if (IsElement("float_array") || IsElement("IDREF_array") || IsElement("Name_array")) { ReadDataArray(); } - else if( IsElement( "technique_common")) + else if (IsElement("technique_common")) { // I don't care for your profiles } - else if( IsElement( "accessor")) + else if (IsElement("accessor")) { - ReadAccessor( sourceID); - } else + ReadAccessor(sourceID); + } + else { // ignore the rest SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "source") == 0) + if (strcmp(mReader->getNodeName(), "source") == 0) { // end of - we're done break; } - else if( strcmp( mReader->getNodeName(), "technique_common") == 0) + else if (strcmp(mReader->getNodeName(), "technique_common") == 0) { // end of another meaningless element - read over it - } else + } + else { // everything else should be punished - ThrowException( "Expected end of element."); + ThrowException("Expected end of element."); } } } @@ -1958,83 +2121,84 @@ void ColladaParser::ReadDataArray() { std::string elmName = mReader->getNodeName(); bool isStringArray = (elmName == "IDREF_array" || elmName == "Name_array"); - bool isEmptyElement = mReader->isEmptyElement(); + bool isEmptyElement = mReader->isEmptyElement(); // read attributes - int indexID = GetAttribute( "id"); - std::string id = mReader->getAttributeValue( indexID); - int indexCount = GetAttribute( "count"); - unsigned int count = (unsigned int) mReader->getAttributeValueAsInt( indexCount); + int indexID = GetAttribute("id"); + std::string id = mReader->getAttributeValue(indexID); + int indexCount = GetAttribute("count"); + unsigned int count = (unsigned int)mReader->getAttributeValueAsInt(indexCount); const char* content = TestTextContent(); - // read values and store inside an array in the data library - mDataLibrary[id] = Data(); - Data& data = mDataLibrary[id]; - data.mIsStringArray = isStringArray; + // read values and store inside an array in the data library + mDataLibrary[id] = Data(); + Data& data = mDataLibrary[id]; + data.mIsStringArray = isStringArray; - // some exporters write empty data arrays, but we need to conserve them anyways because others might reference them - if (content) - { - if( isStringArray) + // some exporters write empty data arrays, but we need to conserve them anyways because others might reference them + if (content) + { + if (isStringArray) { - data.mStrings.reserve( count); + data.mStrings.reserve(count); std::string s; - for( unsigned int a = 0; a < count; a++) + for (unsigned int a = 0; a < count; a++) { - if( *content == 0) - ThrowException( "Expected more values while reading IDREF_array contents."); + if (*content == 0) + ThrowException("Expected more values while reading IDREF_array contents."); s.clear(); - while( !IsSpaceOrNewLine( *content)) + while (!IsSpaceOrNewLine(*content)) s += *content++; - data.mStrings.push_back( s); + data.mStrings.push_back(s); - SkipSpacesAndLineEnd( &content); + SkipSpacesAndLineEnd(&content); } - } else + } + else { - data.mValues.reserve( count); + data.mValues.reserve(count); - for( unsigned int a = 0; a < count; a++) + for (unsigned int a = 0; a < count; a++) { - if( *content == 0) - ThrowException( "Expected more values while reading float_array contents."); + if (*content == 0) + ThrowException("Expected more values while reading float_array contents."); ai_real value; // read a number - content = fast_atoreal_move( content, value); - data.mValues.push_back( value); + content = fast_atoreal_move(content, value); + data.mValues.push_back(value); // skip whitespace after it - SkipSpacesAndLineEnd( &content); + SkipSpacesAndLineEnd(&content); } } } - // test for closing tag - if( !isEmptyElement ) - TestClosing( elmName.c_str()); + // test for closing tag + if (!isEmptyElement) + TestClosing(elmName.c_str()); } // ------------------------------------------------------------------------------------------------ // Reads an accessor and stores it in the global library -void ColladaParser::ReadAccessor( const std::string& pID) +void ColladaParser::ReadAccessor(const std::string& pID) { // read accessor attributes - int attrSource = GetAttribute( "source"); - const char* source = mReader->getAttributeValue( attrSource); - if( source[0] != '#') - ThrowException( format() << "Unknown reference format in url \"" << source << "\" in source attribute of element." ); - int attrCount = GetAttribute( "count"); - unsigned int count = (unsigned int) mReader->getAttributeValueAsInt( attrCount); - int attrOffset = TestAttribute( "offset"); + int attrSource = GetAttribute("source"); + const char* source = mReader->getAttributeValue(attrSource); + if (source[0] != '#') + ThrowException(format() << "Unknown reference format in url \"" << source << "\" in source attribute of element."); + int attrCount = GetAttribute("count"); + unsigned int count = (unsigned int)mReader->getAttributeValueAsInt(attrCount); + int attrOffset = TestAttribute("offset"); unsigned int offset = 0; - if( attrOffset > -1) - offset = (unsigned int) mReader->getAttributeValueAsInt( attrOffset); - int attrStride = TestAttribute( "stride"); + if (attrOffset > -1) + offset = (unsigned int)mReader->getAttributeValueAsInt(attrOffset); + int attrStride = TestAttribute("stride"); unsigned int stride = 1; - if( attrStride > -1) - stride = (unsigned int) mReader->getAttributeValueAsInt( attrStride); + if (attrStride > -1) + stride = (unsigned int)mReader->getAttributeValueAsInt(attrStride); // store in the library under the given ID mAccessorLibrary[pID] = Accessor(); @@ -2042,77 +2206,78 @@ void ColladaParser::ReadAccessor( const std::string& pID) acc.mCount = count; acc.mOffset = offset; acc.mStride = stride; - acc.mSource = source+1; // ignore the leading '#' + acc.mSource = source + 1; // ignore the leading '#' acc.mSize = 0; // gets incremented with every param // and read the components - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "param")) + if (IsElement("param")) { // read data param - int attrName = TestAttribute( "name"); + int attrName = TestAttribute("name"); std::string name; - if( attrName > -1) + if (attrName > -1) { - name = mReader->getAttributeValue( attrName); + name = mReader->getAttributeValue(attrName); // analyse for common type components and store it's sub-offset in the corresponding field /* Cartesian coordinates */ - if( name == "X") acc.mSubOffset[0] = acc.mParams.size(); - else if( name == "Y") acc.mSubOffset[1] = acc.mParams.size(); - else if( name == "Z") acc.mSubOffset[2] = acc.mParams.size(); + if (name == "X") acc.mSubOffset[0] = acc.mParams.size(); + else if (name == "Y") acc.mSubOffset[1] = acc.mParams.size(); + else if (name == "Z") acc.mSubOffset[2] = acc.mParams.size(); /* RGBA colors */ - else if( name == "R") acc.mSubOffset[0] = acc.mParams.size(); - else if( name == "G") acc.mSubOffset[1] = acc.mParams.size(); - else if( name == "B") acc.mSubOffset[2] = acc.mParams.size(); - else if( name == "A") acc.mSubOffset[3] = acc.mParams.size(); + else if (name == "R") acc.mSubOffset[0] = acc.mParams.size(); + else if (name == "G") acc.mSubOffset[1] = acc.mParams.size(); + else if (name == "B") acc.mSubOffset[2] = acc.mParams.size(); + else if (name == "A") acc.mSubOffset[3] = acc.mParams.size(); /* UVWQ (STPQ) texture coordinates */ - else if( name == "S") acc.mSubOffset[0] = acc.mParams.size(); - else if( name == "T") acc.mSubOffset[1] = acc.mParams.size(); - else if( name == "P") acc.mSubOffset[2] = acc.mParams.size(); - // else if( name == "Q") acc.mSubOffset[3] = acc.mParams.size(); - /* 4D uv coordinates are not supported in Assimp */ + else if (name == "S") acc.mSubOffset[0] = acc.mParams.size(); + else if (name == "T") acc.mSubOffset[1] = acc.mParams.size(); + else if (name == "P") acc.mSubOffset[2] = acc.mParams.size(); + // else if( name == "Q") acc.mSubOffset[3] = acc.mParams.size(); + /* 4D uv coordinates are not supported in Assimp */ - /* Generic extra data, interpreted as UV data, too*/ - else if( name == "U") acc.mSubOffset[0] = acc.mParams.size(); - else if( name == "V") acc.mSubOffset[1] = acc.mParams.size(); + /* Generic extra data, interpreted as UV data, too*/ + else if (name == "U") acc.mSubOffset[0] = acc.mParams.size(); + else if (name == "V") acc.mSubOffset[1] = acc.mParams.size(); //else // DefaultLogger::get()->warn( format() << "Unknown accessor parameter \"" << name << "\". Ignoring data channel." ); } // read data type - int attrType = TestAttribute( "type"); - if( attrType > -1) + int attrType = TestAttribute("type"); + if (attrType > -1) { // for the moment we only distinguish between a 4x4 matrix and anything else. // TODO: (thom) I don't have a spec here at work. Check if there are other multi-value types // which should be tested for here. - std::string type = mReader->getAttributeValue( attrType); - if( type == "float4x4") + std::string type = mReader->getAttributeValue(attrType); + if (type == "float4x4") acc.mSize += 16; else acc.mSize += 1; } - acc.mParams.push_back( name); + acc.mParams.push_back(name); // skip remaining stuff of this element, if any SkipElement(); - } else + } + else { - ThrowException( format() << "Unexpected sub element <" << mReader->getNodeName() << "> in tag " ); + ThrowException(format() << "Unexpected sub element <" << mReader->getNodeName() << "> in tag "); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "accessor") != 0) - ThrowException( "Expected end of element."); + if (strcmp(mReader->getNodeName(), "accessor") != 0) + ThrowException("Expected end of element."); break; } } @@ -2120,29 +2285,30 @@ void ColladaParser::ReadAccessor( const std::string& pID) // ------------------------------------------------------------------------------------------------ // Reads input declarations of per-vertex mesh data into the given mesh -void ColladaParser::ReadVertexData( Mesh* pMesh) +void ColladaParser::ReadVertexData(Mesh* pMesh) { // extract the ID of the element. Not that we care, but to catch strange referencing schemes we should warn about - int attrID= GetAttribute( "id"); - pMesh->mVertexID = mReader->getAttributeValue( attrID); + int attrID = GetAttribute("id"); + pMesh->mVertexID = mReader->getAttributeValue(attrID); // a number of elements - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "input")) + if (IsElement("input")) { - ReadInputChannel( pMesh->mPerVertexData); - } else + ReadInputChannel(pMesh->mPerVertexData); + } + else { - ThrowException( format() << "Unexpected sub element <" << mReader->getNodeName() << "> in tag " ); + ThrowException(format() << "Unexpected sub element <" << mReader->getNodeName() << "> in tag "); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "vertices") != 0) - ThrowException( "Expected end of element."); + if (strcmp(mReader->getNodeName(), "vertices") != 0) + ThrowException("Expected end of element."); break; } @@ -2151,79 +2317,79 @@ void ColladaParser::ReadVertexData( Mesh* pMesh) // ------------------------------------------------------------------------------------------------ // Reads input declarations of per-index mesh data into the given mesh -void ColladaParser::ReadIndexData( Mesh* pMesh) +void ColladaParser::ReadIndexData(Mesh* pMesh) { std::vector vcount; std::vector perIndexData; // read primitive count from the attribute - int attrCount = GetAttribute( "count"); - size_t numPrimitives = (size_t) mReader->getAttributeValueAsInt( attrCount); + int attrCount = GetAttribute("count"); + size_t numPrimitives = (size_t)mReader->getAttributeValueAsInt(attrCount); // some mesh types (e.g. tristrips) don't specify primitive count upfront, // so we need to sum up the actual number of primitives while we read the

-tags size_t actualPrimitives = 0; // material subgroup - int attrMaterial = TestAttribute( "material"); + int attrMaterial = TestAttribute("material"); SubMesh subgroup; - if( attrMaterial > -1) - subgroup.mMaterial = mReader->getAttributeValue( attrMaterial); + if (attrMaterial > -1) + subgroup.mMaterial = mReader->getAttributeValue(attrMaterial); // distinguish between polys and triangles std::string elementName = mReader->getNodeName(); PrimitiveType primType = Prim_Invalid; - if( IsElement( "lines")) + if (IsElement("lines")) primType = Prim_Lines; - else if( IsElement( "linestrips")) + else if (IsElement("linestrips")) primType = Prim_LineStrip; - else if( IsElement( "polygons")) + else if (IsElement("polygons")) primType = Prim_Polygon; - else if( IsElement( "polylist")) + else if (IsElement("polylist")) primType = Prim_Polylist; - else if( IsElement( "triangles")) + else if (IsElement("triangles")) primType = Prim_Triangles; - else if( IsElement( "trifans")) + else if (IsElement("trifans")) primType = Prim_TriFans; - else if( IsElement( "tristrips")) + else if (IsElement("tristrips")) primType = Prim_TriStrips; - ai_assert( primType != Prim_Invalid); + ai_assert(primType != Prim_Invalid); // also a number of elements, but in addition a

primitive collection and probably index counts for all primitives - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "input")) + if (IsElement("input")) { - ReadInputChannel( perIndexData); + ReadInputChannel(perIndexData); } - else if( IsElement( "vcount")) + else if (IsElement("vcount")) { - if( !mReader->isEmptyElement()) + if (!mReader->isEmptyElement()) { if (numPrimitives) // It is possible to define a mesh without any primitives { // case - specifies the number of indices for each polygon const char* content = GetTextContent(); - vcount.reserve( numPrimitives); - for( unsigned int a = 0; a < numPrimitives; a++) + vcount.reserve(numPrimitives); + for (unsigned int a = 0; a < numPrimitives; a++) { - if( *content == 0) - ThrowException( "Expected more values while reading contents."); + if (*content == 0) + ThrowException("Expected more values while reading contents."); // read a number - vcount.push_back( (size_t) strtoul10( content, &content)); + vcount.push_back((size_t)strtoul10(content, &content)); // skip whitespace after it - SkipSpacesAndLineEnd( &content); + SkipSpacesAndLineEnd(&content); } } - TestClosing( "vcount"); + TestClosing("vcount"); } } - else if( IsElement( "p")) + else if (IsElement("p")) { - if( !mReader->isEmptyElement()) + if (!mReader->isEmptyElement()) { // now here the actual fun starts - these are the indices to construct the mesh data from actualPrimitives += ReadPrimitives(pMesh, perIndexData, numPrimitives, vcount, primType); @@ -2232,23 +2398,25 @@ void ColladaParser::ReadIndexData( Mesh* pMesh) else if (IsElement("extra")) { SkipElement("extra"); - } else if ( IsElement("ph")) { + } + else if (IsElement("ph")) { SkipElement("ph"); - } else { - ThrowException( format() << "Unexpected sub element <" << mReader->getNodeName() << "> in tag <" << elementName << ">" ); + } + else { + ThrowException(format() << "Unexpected sub element <" << mReader->getNodeName() << "> in tag <" << elementName << ">"); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( mReader->getNodeName() != elementName) - ThrowException( format() << "Expected end of <" << elementName << "> element." ); + if (mReader->getNodeName() != elementName) + ThrowException(format() << "Expected end of <" << elementName << "> element."); break; } } #ifdef ASSIMP_BUILD_DEBUG - if (primType != Prim_TriFans && primType != Prim_TriStrips && primType != Prim_LineStrip && + if (primType != Prim_TriFans && primType != Prim_TriStrips && primType != Prim_LineStrip && primType != Prim_Lines) { // this is ONLY to workaround a bug in SketchUp 15.3.331 where it writes the wrong 'count' when it writes out the 'lines'. ai_assert(actualPrimitives == numPrimitives); } @@ -2261,42 +2429,42 @@ void ColladaParser::ReadIndexData( Mesh* pMesh) // ------------------------------------------------------------------------------------------------ // Reads a single input channel element and stores it in the given array, if valid -void ColladaParser::ReadInputChannel( std::vector& poChannels) +void ColladaParser::ReadInputChannel(std::vector& poChannels) { InputChannel channel; // read semantic - int attrSemantic = GetAttribute( "semantic"); - std::string semantic = mReader->getAttributeValue( attrSemantic); - channel.mType = GetTypeForSemantic( semantic); + int attrSemantic = GetAttribute("semantic"); + std::string semantic = mReader->getAttributeValue(attrSemantic); + channel.mType = GetTypeForSemantic(semantic); // read source - int attrSource = GetAttribute( "source"); - const char* source = mReader->getAttributeValue( attrSource); - if( source[0] != '#') - ThrowException( format() << "Unknown reference format in url \"" << source << "\" in source attribute of element." ); - channel.mAccessor = source+1; // skipping the leading #, hopefully the remaining text is the accessor ID only + int attrSource = GetAttribute("source"); + const char* source = mReader->getAttributeValue(attrSource); + if (source[0] != '#') + ThrowException(format() << "Unknown reference format in url \"" << source << "\" in source attribute of element."); + channel.mAccessor = source + 1; // skipping the leading #, hopefully the remaining text is the accessor ID only // read index offset, if per-index - int attrOffset = TestAttribute( "offset"); - if( attrOffset > -1) - channel.mOffset = mReader->getAttributeValueAsInt( attrOffset); + int attrOffset = TestAttribute("offset"); + if (attrOffset > -1) + channel.mOffset = mReader->getAttributeValueAsInt(attrOffset); // read set if texture coordinates - if(channel.mType == IT_Texcoord || channel.mType == IT_Color){ + if (channel.mType == IT_Texcoord || channel.mType == IT_Color) { int attrSet = TestAttribute("set"); - if(attrSet > -1){ - attrSet = mReader->getAttributeValueAsInt( attrSet); - if(attrSet < 0) - ThrowException( format() << "Invalid index \"" << (attrSet) << "\" in set attribute of element" ); + if (attrSet > -1) { + attrSet = mReader->getAttributeValueAsInt(attrSet); + if (attrSet < 0) + ThrowException(format() << "Invalid index \"" << (attrSet) << "\" in set attribute of element"); channel.mIndex = attrSet; } } // store, if valid type - if( channel.mType != IT_Invalid) - poChannels.push_back( channel); + if (channel.mType != IT_Invalid) + poChannels.push_back(channel); // skip remaining stuff of this element, if any SkipElement(); @@ -2304,116 +2472,118 @@ void ColladaParser::ReadInputChannel( std::vector& poChannels) // ------------------------------------------------------------------------------------------------ // Reads a

primitive index list and assembles the mesh data into the given mesh -size_t ColladaParser::ReadPrimitives( Mesh* pMesh, std::vector& pPerIndexChannels, +size_t ColladaParser::ReadPrimitives(Mesh* pMesh, std::vector& pPerIndexChannels, size_t pNumPrimitives, const std::vector& pVCount, PrimitiveType pPrimType) { // determine number of indices coming per vertex // find the offset index for all per-vertex channels size_t numOffsets = 1; size_t perVertexOffset = SIZE_MAX; // invalid value - for( const InputChannel& channel : pPerIndexChannels) + for (const InputChannel& channel : pPerIndexChannels) { - numOffsets = std::max( numOffsets, channel.mOffset+1); - if( channel.mType == IT_Vertex) + numOffsets = std::max(numOffsets, channel.mOffset + 1); + if (channel.mType == IT_Vertex) perVertexOffset = channel.mOffset; } // determine the expected number of indices size_t expectedPointCount = 0; - switch( pPrimType) + switch (pPrimType) { - case Prim_Polylist: - { - for( size_t i : pVCount) - expectedPointCount += i; - break; - } - case Prim_Lines: - expectedPointCount = 2 * pNumPrimitives; - break; - case Prim_Triangles: - expectedPointCount = 3 * pNumPrimitives; - break; - default: - // other primitive types don't state the index count upfront... we need to guess - break; + case Prim_Polylist: + { + for (size_t i : pVCount) + expectedPointCount += i; + break; + } + case Prim_Lines: + expectedPointCount = 2 * pNumPrimitives; + break; + case Prim_Triangles: + expectedPointCount = 3 * pNumPrimitives; + break; + default: + // other primitive types don't state the index count upfront... we need to guess + break; } // and read all indices into a temporary array std::vector indices; - if( expectedPointCount > 0) - indices.reserve( expectedPointCount * numOffsets); + if (expectedPointCount > 0) + indices.reserve(expectedPointCount * numOffsets); if (pNumPrimitives > 0) // It is possible to not contain any indices { const char* content = GetTextContent(); - while( *content != 0) + while (*content != 0) { // read a value. // Hack: (thom) Some exporters put negative indices sometimes. We just try to carry on anyways. - int value = std::max( 0, strtol10( content, &content)); - indices.push_back( size_t( value)); + int value = std::max(0, strtol10(content, &content)); + indices.push_back(size_t(value)); // skip whitespace after it - SkipSpacesAndLineEnd( &content); + SkipSpacesAndLineEnd(&content); } } - // complain if the index count doesn't fit - if( expectedPointCount > 0 && indices.size() != expectedPointCount * numOffsets) { + // complain if the index count doesn't fit + if (expectedPointCount > 0 && indices.size() != expectedPointCount * numOffsets) { if (pPrimType == Prim_Lines) { // HACK: We just fix this number since SketchUp 15.3.331 writes the wrong 'count' for 'lines' - ReportWarning( "Expected different index count in

element, %d instead of %d.", indices.size(), expectedPointCount * numOffsets); + ReportWarning("Expected different index count in

element, %zu instead of %zu.", indices.size(), expectedPointCount * numOffsets); pNumPrimitives = (indices.size() / numOffsets) / 2; - } else - ThrowException( "Expected different index count in

element."); + } + else + ThrowException("Expected different index count in

element."); - } else if( expectedPointCount == 0 && (indices.size() % numOffsets) != 0) - ThrowException( "Expected different index count in

element."); + } + else if (expectedPointCount == 0 && (indices.size() % numOffsets) != 0) + ThrowException("Expected different index count in

element."); - // find the data for all sources - for( std::vector::iterator it = pMesh->mPerVertexData.begin(); it != pMesh->mPerVertexData.end(); ++it) + // find the data for all sources + for (std::vector::iterator it = pMesh->mPerVertexData.begin(); it != pMesh->mPerVertexData.end(); ++it) { InputChannel& input = *it; - if( input.mResolved) + if (input.mResolved) continue; // find accessor - input.mResolved = &ResolveLibraryReference( mAccessorLibrary, input.mAccessor); + input.mResolved = &ResolveLibraryReference(mAccessorLibrary, input.mAccessor); // resolve accessor's data pointer as well, if necessary const Accessor* acc = input.mResolved; - if( !acc->mData) - acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource); + if (!acc->mData) + acc->mData = &ResolveLibraryReference(mDataLibrary, acc->mSource); } // and the same for the per-index channels - for( std::vector::iterator it = pPerIndexChannels.begin(); it != pPerIndexChannels.end(); ++it) + for (std::vector::iterator it = pPerIndexChannels.begin(); it != pPerIndexChannels.end(); ++it) { InputChannel& input = *it; - if( input.mResolved) + if (input.mResolved) continue; // ignore vertex pointer, it doesn't refer to an accessor - if( input.mType == IT_Vertex) + if (input.mType == IT_Vertex) { // warn if the vertex channel does not refer to the element in the same mesh - if( input.mAccessor != pMesh->mVertexID) - ThrowException( "Unsupported vertex referencing scheme."); + if (input.mAccessor != pMesh->mVertexID) + ThrowException("Unsupported vertex referencing scheme."); continue; } // find accessor - input.mResolved = &ResolveLibraryReference( mAccessorLibrary, input.mAccessor); + input.mResolved = &ResolveLibraryReference(mAccessorLibrary, input.mAccessor); // resolve accessor's data pointer as well, if necessary const Accessor* acc = input.mResolved; - if( !acc->mData) - acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource); + if (!acc->mData) + acc->mData = &ResolveLibraryReference(mDataLibrary, acc->mSource); } // For continued primitives, the given count does not come all in one

, but only one primitive per

size_t numPrimitives = pNumPrimitives; - if( pPrimType == Prim_TriFans || pPrimType == Prim_Polygon) + if (pPrimType == Prim_TriFans || pPrimType == Prim_Polygon) numPrimitives = 1; // For continued primitives, the given count is actually the number of

's inside the parent tag - if ( pPrimType == Prim_TriStrips){ + if (pPrimType == Prim_TriStrips) { size_t numberOfVertices = indices.size() / numOffsets; numPrimitives = numberOfVertices - 2; } @@ -2422,66 +2592,66 @@ size_t ColladaParser::ReadPrimitives( Mesh* pMesh, std::vector& pP numPrimitives = numberOfVertices - 1; } - pMesh->mFaceSize.reserve( numPrimitives); - pMesh->mFacePosIndices.reserve( indices.size() / numOffsets); + pMesh->mFaceSize.reserve(numPrimitives); + pMesh->mFacePosIndices.reserve(indices.size() / numOffsets); size_t polylistStartVertex = 0; for (size_t currentPrimitive = 0; currentPrimitive < numPrimitives; currentPrimitive++) { // determine number of points for this primitive size_t numPoints = 0; - switch( pPrimType) + switch (pPrimType) { - case Prim_Lines: - numPoints = 2; - for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++) - CopyVertex(currentVertex, numOffsets, numPoints, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); - break; - case Prim_LineStrip: - numPoints = 2; - for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++) - CopyVertex(currentVertex, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); - break; - case Prim_Triangles: - numPoints = 3; - for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++) - CopyVertex(currentVertex, numOffsets, numPoints, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); - break; - case Prim_TriStrips: - numPoints = 3; - ReadPrimTriStrips(numOffsets, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); - break; - case Prim_Polylist: - numPoints = pVCount[currentPrimitive]; - for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++) - CopyVertex(polylistStartVertex + currentVertex, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, 0, indices); - polylistStartVertex += numPoints; - break; - case Prim_TriFans: - case Prim_Polygon: - numPoints = indices.size() / numOffsets; - for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++) - CopyVertex(currentVertex, numOffsets, numPoints, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); - break; - default: - // LineStrip is not supported due to expected index unmangling - ThrowException( "Unsupported primitive type."); - break; + case Prim_Lines: + numPoints = 2; + for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++) + CopyVertex(currentVertex, numOffsets, numPoints, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); + break; + case Prim_LineStrip: + numPoints = 2; + for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++) + CopyVertex(currentVertex, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); + break; + case Prim_Triangles: + numPoints = 3; + for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++) + CopyVertex(currentVertex, numOffsets, numPoints, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); + break; + case Prim_TriStrips: + numPoints = 3; + ReadPrimTriStrips(numOffsets, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); + break; + case Prim_Polylist: + numPoints = pVCount[currentPrimitive]; + for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++) + CopyVertex(polylistStartVertex + currentVertex, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, 0, indices); + polylistStartVertex += numPoints; + break; + case Prim_TriFans: + case Prim_Polygon: + numPoints = indices.size() / numOffsets; + for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++) + CopyVertex(currentVertex, numOffsets, numPoints, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); + break; + default: + // LineStrip is not supported due to expected index unmangling + ThrowException("Unsupported primitive type."); + break; } // store the face size to later reconstruct the face from - pMesh->mFaceSize.push_back( numPoints); + pMesh->mFaceSize.push_back(numPoints); } // if I ever get my hands on that guy who invented this steaming pile of indirection... - TestClosing( "p"); + TestClosing("p"); 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 and 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& pPerIndexChannels, size_t currentPrimitive, const std::vector& indices){ +void ColladaParser::CopyVertex(size_t currentVertex, size_t numOffsets, size_t numPoints, size_t perVertexOffset, Mesh* pMesh, std::vector& pPerIndexChannels, size_t currentPrimitive, const std::vector& indices) { // calculate the base offset of the vertex whose attributes we ant to copy size_t baseOffset = currentPrimitive * numOffsets * numPoints + currentVertex * numOffsets; @@ -2499,8 +2669,8 @@ void ColladaParser::CopyVertex(size_t currentVertex, size_t numOffsets, size_t n pMesh->mFacePosIndices.push_back(indices[baseOffset + perVertexOffset]); } -void ColladaParser::ReadPrimTriStrips(size_t numOffsets, size_t perVertexOffset, Mesh* pMesh, std::vector& pPerIndexChannels, size_t currentPrimitive, const std::vector& indices){ - if (currentPrimitive % 2 != 0){ +void ColladaParser::ReadPrimTriStrips(size_t numOffsets, size_t perVertexOffset, Mesh* pMesh, std::vector& pPerIndexChannels, size_t currentPrimitive, const std::vector& indices) { + if (currentPrimitive % 2 != 0) { //odd tristrip triangles need their indices mangled, to preserve winding direction CopyVertex(1, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); CopyVertex(0, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); @@ -2515,108 +2685,110 @@ void ColladaParser::ReadPrimTriStrips(size_t numOffsets, size_t perVertexOffset, // ------------------------------------------------------------------------------------------------ // Extracts a single object from an input channel and stores it in the appropriate mesh data array -void ColladaParser::ExtractDataObjectFromChannel( const InputChannel& pInput, size_t pLocalIndex, Mesh* pMesh) +void ColladaParser::ExtractDataObjectFromChannel(const InputChannel& pInput, size_t pLocalIndex, Mesh* pMesh) { // ignore vertex referrer - we handle them that separate - if( pInput.mType == IT_Vertex) + if (pInput.mType == IT_Vertex) return; const Accessor& acc = *pInput.mResolved; - if( pLocalIndex >= acc.mCount) - ThrowException( format() << "Invalid data index (" << pLocalIndex << "/" << acc.mCount << ") in primitive specification" ); + if (pLocalIndex >= acc.mCount) + ThrowException(format() << "Invalid data index (" << pLocalIndex << "/" << acc.mCount << ") in primitive specification"); // get a pointer to the start of the data object referred to by the accessor and the local index - const ai_real* dataObject = &(acc.mData->mValues[0]) + acc.mOffset + pLocalIndex* acc.mStride; + const ai_real* dataObject = &(acc.mData->mValues[0]) + acc.mOffset + pLocalIndex * acc.mStride; // assemble according to the accessors component sub-offset list. We don't care, yet, // what kind of object exactly we're extracting here ai_real obj[4]; - for( size_t c = 0; c < 4; ++c) + for (size_t c = 0; c < 4; ++c) obj[c] = dataObject[acc.mSubOffset[c]]; // now we reinterpret it according to the type we're reading here - switch( pInput.mType) + switch (pInput.mType) { - case IT_Position: // ignore all position streams except 0 - there can be only one position - if( pInput.mIndex == 0) - pMesh->mPositions.push_back( aiVector3D( obj[0], obj[1], obj[2])); - else - ASSIMP_LOG_ERROR("Collada: just one vertex position stream supported"); - break; - case IT_Normal: - // pad to current vertex count if necessary - if( pMesh->mNormals.size() < pMesh->mPositions.size()-1) - pMesh->mNormals.insert( pMesh->mNormals.end(), pMesh->mPositions.size() - pMesh->mNormals.size() - 1, aiVector3D( 0, 1, 0)); + case IT_Position: // ignore all position streams except 0 - there can be only one position + if (pInput.mIndex == 0) + pMesh->mPositions.push_back(aiVector3D(obj[0], obj[1], obj[2])); + else + ASSIMP_LOG_ERROR("Collada: just one vertex position stream supported"); + break; + case IT_Normal: + // pad to current vertex count if necessary + if (pMesh->mNormals.size() < pMesh->mPositions.size() - 1) + pMesh->mNormals.insert(pMesh->mNormals.end(), pMesh->mPositions.size() - pMesh->mNormals.size() - 1, aiVector3D(0, 1, 0)); - // ignore all normal streams except 0 - there can be only one normal - if( pInput.mIndex == 0) - pMesh->mNormals.push_back( aiVector3D( obj[0], obj[1], obj[2])); - else - ASSIMP_LOG_ERROR("Collada: just one vertex normal stream supported"); - break; - case IT_Tangent: - // pad to current vertex count if necessary - if( pMesh->mTangents.size() < pMesh->mPositions.size()-1) - pMesh->mTangents.insert( pMesh->mTangents.end(), pMesh->mPositions.size() - pMesh->mTangents.size() - 1, aiVector3D( 1, 0, 0)); + // ignore all normal streams except 0 - there can be only one normal + if (pInput.mIndex == 0) + pMesh->mNormals.push_back(aiVector3D(obj[0], obj[1], obj[2])); + else + ASSIMP_LOG_ERROR("Collada: just one vertex normal stream supported"); + break; + case IT_Tangent: + // pad to current vertex count if necessary + if (pMesh->mTangents.size() < pMesh->mPositions.size() - 1) + pMesh->mTangents.insert(pMesh->mTangents.end(), pMesh->mPositions.size() - pMesh->mTangents.size() - 1, aiVector3D(1, 0, 0)); - // ignore all tangent streams except 0 - there can be only one tangent - if( pInput.mIndex == 0) - pMesh->mTangents.push_back( aiVector3D( obj[0], obj[1], obj[2])); - else - ASSIMP_LOG_ERROR("Collada: just one vertex tangent stream supported"); - break; - case IT_Bitangent: - // pad to current vertex count if necessary - if( pMesh->mBitangents.size() < pMesh->mPositions.size()-1) - pMesh->mBitangents.insert( pMesh->mBitangents.end(), pMesh->mPositions.size() - pMesh->mBitangents.size() - 1, aiVector3D( 0, 0, 1)); + // ignore all tangent streams except 0 - there can be only one tangent + if (pInput.mIndex == 0) + pMesh->mTangents.push_back(aiVector3D(obj[0], obj[1], obj[2])); + else + ASSIMP_LOG_ERROR("Collada: just one vertex tangent stream supported"); + break; + case IT_Bitangent: + // pad to current vertex count if necessary + if (pMesh->mBitangents.size() < pMesh->mPositions.size() - 1) + pMesh->mBitangents.insert(pMesh->mBitangents.end(), pMesh->mPositions.size() - pMesh->mBitangents.size() - 1, aiVector3D(0, 0, 1)); - // ignore all bitangent streams except 0 - there can be only one bitangent - if( pInput.mIndex == 0) - pMesh->mBitangents.push_back( aiVector3D( obj[0], obj[1], obj[2])); - else - ASSIMP_LOG_ERROR("Collada: just one vertex bitangent stream supported"); - break; - case IT_Texcoord: - // up to 4 texture coord sets are fine, ignore the others - if( pInput.mIndex < AI_MAX_NUMBER_OF_TEXTURECOORDS) + // ignore all bitangent streams except 0 - there can be only one bitangent + if (pInput.mIndex == 0) + pMesh->mBitangents.push_back(aiVector3D(obj[0], obj[1], obj[2])); + else + ASSIMP_LOG_ERROR("Collada: just one vertex bitangent stream supported"); + break; + case IT_Texcoord: + // up to 4 texture coord sets are fine, ignore the others + if (pInput.mIndex < AI_MAX_NUMBER_OF_TEXTURECOORDS) + { + // pad to current vertex count if necessary + if (pMesh->mTexCoords[pInput.mIndex].size() < pMesh->mPositions.size() - 1) + pMesh->mTexCoords[pInput.mIndex].insert(pMesh->mTexCoords[pInput.mIndex].end(), + pMesh->mPositions.size() - pMesh->mTexCoords[pInput.mIndex].size() - 1, aiVector3D(0, 0, 0)); + + pMesh->mTexCoords[pInput.mIndex].push_back(aiVector3D(obj[0], obj[1], obj[2])); + if (0 != acc.mSubOffset[2] || 0 != acc.mSubOffset[3]) /* hack ... consider cleaner solution */ + pMesh->mNumUVComponents[pInput.mIndex] = 3; + } + else + { + ASSIMP_LOG_ERROR("Collada: too many texture coordinate sets. Skipping."); + } + break; + case IT_Color: + // up to 4 color sets are fine, ignore the others + if (pInput.mIndex < AI_MAX_NUMBER_OF_COLOR_SETS) + { + // pad to current vertex count if necessary + if (pMesh->mColors[pInput.mIndex].size() < pMesh->mPositions.size() - 1) + pMesh->mColors[pInput.mIndex].insert(pMesh->mColors[pInput.mIndex].end(), + pMesh->mPositions.size() - pMesh->mColors[pInput.mIndex].size() - 1, aiColor4D(0, 0, 0, 1)); + + aiColor4D result(0, 0, 0, 1); + for (size_t i = 0; i < pInput.mResolved->mSize; ++i) { - // pad to current vertex count if necessary - if( pMesh->mTexCoords[pInput.mIndex].size() < pMesh->mPositions.size()-1) - pMesh->mTexCoords[pInput.mIndex].insert( pMesh->mTexCoords[pInput.mIndex].end(), - pMesh->mPositions.size() - pMesh->mTexCoords[pInput.mIndex].size() - 1, aiVector3D( 0, 0, 0)); - - pMesh->mTexCoords[pInput.mIndex].push_back( aiVector3D( obj[0], obj[1], obj[2])); - if (0 != acc.mSubOffset[2] || 0 != acc.mSubOffset[3]) /* hack ... consider cleaner solution */ - pMesh->mNumUVComponents[pInput.mIndex]=3; - } else - { - ASSIMP_LOG_ERROR("Collada: too many texture coordinate sets. Skipping."); + result[static_cast(i)] = obj[pInput.mResolved->mSubOffset[i]]; } - break; - case IT_Color: - // up to 4 color sets are fine, ignore the others - if( pInput.mIndex < AI_MAX_NUMBER_OF_COLOR_SETS) - { - // pad to current vertex count if necessary - if( pMesh->mColors[pInput.mIndex].size() < pMesh->mPositions.size()-1) - pMesh->mColors[pInput.mIndex].insert( pMesh->mColors[pInput.mIndex].end(), - pMesh->mPositions.size() - pMesh->mColors[pInput.mIndex].size() - 1, aiColor4D( 0, 0, 0, 1)); + pMesh->mColors[pInput.mIndex].push_back(result); + } + else + { + ASSIMP_LOG_ERROR("Collada: too many vertex color sets. Skipping."); + } - aiColor4D result(0, 0, 0, 1); - for (size_t i = 0; i < pInput.mResolved->mSize; ++i) - { - result[static_cast(i)] = obj[pInput.mResolved->mSubOffset[i]]; - } - pMesh->mColors[pInput.mIndex].push_back(result); - } else - { - ASSIMP_LOG_ERROR("Collada: too many vertex color sets. Skipping."); - } - - break; - default: - // IT_Invalid and IT_Vertex - ai_assert(false && "shouldn't ever get here"); + break; + default: + // IT_Invalid and IT_Vertex + ai_assert(false && "shouldn't ever get here"); } } @@ -2624,25 +2796,25 @@ void ColladaParser::ExtractDataObjectFromChannel( const InputChannel& pInput, si // Reads the library of node hierarchies and scene parts void ColladaParser::ReadSceneLibrary() { - if( mReader->isEmptyElement()) + if (mReader->isEmptyElement()) return; - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { // a visual scene - generate root node under its ID and let ReadNode() do the recursive work - if( IsElement( "visual_scene")) + if (IsElement("visual_scene")) { // read ID. Is optional according to the spec, but how on earth should a scene_instance refer to it then? - int indexID = GetAttribute( "id"); - const char* attrID = mReader->getAttributeValue( indexID); + int indexID = GetAttribute("id"); + const char* attrID = mReader->getAttributeValue(indexID); // read name if given. - int indexName = TestAttribute( "name"); + int indexName = TestAttribute("name"); const char* attrName = "unnamed"; - if( indexName > -1) - attrName = mReader->getAttributeValue( indexName); + if (indexName > -1) + attrName = mReader->getAttributeValue(indexName); // create a node and store it in the library under its ID Node* node = new Node; @@ -2650,55 +2822,56 @@ void ColladaParser::ReadSceneLibrary() node->mName = attrName; mNodeLibrary[node->mID] = node; - ReadSceneNode( node); - } else + ReadSceneNode(node); + } + else { // ignore the rest SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "library_visual_scenes") == 0) + if (strcmp(mReader->getNodeName(), "library_visual_scenes") == 0) //ThrowException( "Expected end of \"library_visual_scenes\" element."); - break; + break; } } } // ------------------------------------------------------------------------------------------------ // Reads a scene node's contents including children and stores it in the given node -void ColladaParser::ReadSceneNode( Node* pNode) +void ColladaParser::ReadSceneNode(Node* pNode) { // quit immediately on elements - if( mReader->isEmptyElement()) + if (mReader->isEmptyElement()) return; - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "node")) + if (IsElement("node")) { Node* child = new Node; - int attrID = TestAttribute( "id"); - if( attrID > -1) - child->mID = mReader->getAttributeValue( attrID); - int attrSID = TestAttribute( "sid"); - if( attrSID > -1) - child->mSID = mReader->getAttributeValue( attrSID); + int attrID = TestAttribute("id"); + if (attrID > -1) + child->mID = mReader->getAttributeValue(attrID); + int attrSID = TestAttribute("sid"); + if (attrSID > -1) + child->mSID = mReader->getAttributeValue(attrSID); - int attrName = TestAttribute( "name"); - if( attrName > -1) - child->mName = mReader->getAttributeValue( attrName); + int attrName = TestAttribute("name"); + if (attrName > -1) + child->mName = mReader->getAttributeValue(attrName); // TODO: (thom) support SIDs // ai_assert( TestAttribute( "sid") == -1); if (pNode) { - pNode->mChildren.push_back( child); + pNode->mChildren.push_back(child); child->mParent = pNode; } else @@ -2709,26 +2882,26 @@ void ColladaParser::ReadSceneNode( Node* pNode) } // read on recursively from there - ReadSceneNode( child); + ReadSceneNode(child); continue; } // For any further stuff we need a valid node to work on else if (!pNode) continue; - if( IsElement( "lookat")) - ReadNodeTransformation( pNode, TF_LOOKAT); - else if( IsElement( "matrix")) - ReadNodeTransformation( pNode, TF_MATRIX); - else if( IsElement( "rotate")) - ReadNodeTransformation( pNode, TF_ROTATE); - else if( IsElement( "scale")) - ReadNodeTransformation( pNode, TF_SCALE); - else if( IsElement( "skew")) - ReadNodeTransformation( pNode, TF_SKEW); - else if( IsElement( "translate")) - ReadNodeTransformation( pNode, TF_TRANSLATE); - else if( IsElement( "render") && pNode->mParent == NULL && 0 == pNode->mPrimaryCamera.length()) + if (IsElement("lookat")) + ReadNodeTransformation(pNode, TF_LOOKAT); + else if (IsElement("matrix")) + ReadNodeTransformation(pNode, TF_MATRIX); + else if (IsElement("rotate")) + ReadNodeTransformation(pNode, TF_ROTATE); + else if (IsElement("scale")) + ReadNodeTransformation(pNode, TF_SCALE); + else if (IsElement("skew")) + ReadNodeTransformation(pNode, TF_SKEW); + else if (IsElement("translate")) + ReadNodeTransformation(pNode, TF_TRANSLATE); + else if (IsElement("render") && pNode->mParent == NULL && 0 == pNode->mPrimaryCamera.length()) { // ... scene evaluation or, in other words, postprocessing pipeline, // or, again in other words, a turing-complete description how to @@ -2741,14 +2914,14 @@ void ColladaParser::ReadSceneNode( Node* pNode) if (s[0] != '#') ASSIMP_LOG_ERROR("Collada: Unresolved reference format of camera"); else - pNode->mPrimaryCamera = s+1; + pNode->mPrimaryCamera = s + 1; } } - else if( IsElement( "instance_node")) + else if (IsElement("instance_node")) { // find the node in the library - int attrID = TestAttribute( "url"); - if( attrID != -1) + int attrID = TestAttribute("url"); + if (attrID != -1) { const char* s = mReader->getAttributeValue(attrID); if (s[0] != '#') @@ -2756,16 +2929,16 @@ void ColladaParser::ReadSceneNode( Node* pNode) else { pNode->mNodeInstances.push_back(NodeInstance()); - pNode->mNodeInstances.back().mNode = s+1; + pNode->mNodeInstances.back().mNode = s + 1; } } } - else if( IsElement( "instance_geometry") || IsElement( "instance_controller")) + else if (IsElement("instance_geometry") || IsElement("instance_controller")) { // Reference to a mesh or controller, with possible material associations - ReadNodeGeometry( pNode); + ReadNodeGeometry(pNode); } - else if( IsElement( "instance_light")) + else if (IsElement("instance_light")) { // Reference to a light, name given in 'url' attribute int attrID = TestAttribute("url"); @@ -2773,15 +2946,15 @@ void ColladaParser::ReadSceneNode( Node* pNode) ASSIMP_LOG_WARN("Collada: Expected url attribute in element"); else { - const char* url = mReader->getAttributeValue( attrID); - if( url[0] != '#') - ThrowException( "Unknown reference format in element"); + const char* url = mReader->getAttributeValue(attrID); + if (url[0] != '#') + ThrowException("Unknown reference format in element"); pNode->mLights.push_back(LightInstance()); - pNode->mLights.back().mLight = url+1; + pNode->mLights.back().mLight = url + 1; } } - else if( IsElement( "instance_camera")) + else if (IsElement("instance_camera")) { // Reference to a camera, name given in 'url' attribute int attrID = TestAttribute("url"); @@ -2789,12 +2962,12 @@ void ColladaParser::ReadSceneNode( Node* pNode) ASSIMP_LOG_WARN("Collada: Expected url attribute in element"); else { - const char* url = mReader->getAttributeValue( attrID); - if( url[0] != '#') - ThrowException( "Unknown reference format in element"); + const char* url = mReader->getAttributeValue(attrID); + if (url[0] != '#') + ThrowException("Unknown reference format in element"); pNode->mCameras.push_back(CameraInstance()); - pNode->mCameras.back().mCamera = url+1; + pNode->mCameras.back().mCamera = url + 1; } } else @@ -2803,7 +2976,7 @@ void ColladaParser::ReadSceneNode( Node* pNode) SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { break; } } @@ -2811,9 +2984,9 @@ void ColladaParser::ReadSceneNode( Node* pNode) // ------------------------------------------------------------------------------------------------ // Reads a node transformation entry of the given type and adds it to the given node's transformation list. -void ColladaParser::ReadNodeTransformation( Node* pNode, TransformType pType) +void ColladaParser::ReadNodeTransformation(Node* pNode, TransformType pType) { - if( mReader->isEmptyElement()) + if (mReader->isEmptyElement()) return; std::string tagName = mReader->getNodeName(); @@ -2822,38 +2995,38 @@ void ColladaParser::ReadNodeTransformation( Node* pNode, TransformType pType) tf.mType = pType; // read SID - int indexSID = TestAttribute( "sid"); - if( indexSID >= 0) - tf.mID = mReader->getAttributeValue( indexSID); + int indexSID = TestAttribute("sid"); + if (indexSID >= 0) + tf.mID = mReader->getAttributeValue(indexSID); // how many parameters to read per transformation type static const unsigned int sNumParameters[] = { 9, 4, 3, 3, 7, 16 }; const char* content = GetTextContent(); // read as many parameters and store in the transformation - for( unsigned int a = 0; a < sNumParameters[pType]; a++) + for (unsigned int a = 0; a < sNumParameters[pType]; a++) { // read a number - content = fast_atoreal_move( content, tf.f[a]); + content = fast_atoreal_move(content, tf.f[a]); // skip whitespace after it - SkipSpacesAndLineEnd( &content); + SkipSpacesAndLineEnd(&content); } // place the transformation at the queue of the node - pNode->mTransforms.push_back( tf); + pNode->mTransforms.push_back(tf); // and consume the closing tag - TestClosing( tagName.c_str()); + TestClosing(tagName.c_str()); } // ------------------------------------------------------------------------------------------------ // Processes bind_vertex_input and bind elements -void ColladaParser::ReadMaterialVertexInputBinding( Collada::SemanticMappingTable& tbl) +void ColladaParser::ReadMaterialVertexInputBinding(Collada::SemanticMappingTable& tbl) { - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "bind_vertex_input")) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { + if (IsElement("bind_vertex_input")) { Collada::InputSemanticMapEntry vn; @@ -2863,7 +3036,7 @@ void ColladaParser::ReadMaterialVertexInputBinding( Collada::SemanticMappingTabl // input semantic n = GetAttribute("input_semantic"); - vn.mType = GetTypeForSemantic( mReader->getAttributeValue(n) ); + vn.mType = GetTypeForSemantic(mReader->getAttributeValue(n)); // index of input set n = TestAttribute("input_set"); @@ -2872,103 +3045,124 @@ void ColladaParser::ReadMaterialVertexInputBinding( Collada::SemanticMappingTabl tbl.mMap[s] = vn; } - else if( IsElement( "bind")) { + else if (IsElement("bind")) { ASSIMP_LOG_WARN("Collada: Found unsupported element"); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "instance_material") == 0) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { + if (strcmp(mReader->getNodeName(), "instance_material") == 0) break; } } } +void Assimp::ColladaParser::ReadEmbeddedTextures(ZipArchiveIOSystem& zip_archive) +{ + // Attempt to load any undefined Collada::Image in ImageLibrary + for (ImageLibrary::iterator it = mImageLibrary.begin(); it != mImageLibrary.end(); ++it) { + Collada::Image &image = (*it).second; + + if (image.mImageData.empty()) { + std::unique_ptr image_file(zip_archive.Open(image.mFileName.c_str())); + if (image_file) { + image.mImageData.resize(image_file->FileSize()); + image_file->Read(image.mImageData.data(), image_file->FileSize(), 1); + image.mEmbeddedFormat = BaseImporter::GetExtension(image.mFileName); + if (image.mEmbeddedFormat == "jpeg") { + image.mEmbeddedFormat = "jpg"; + } + } + } + } +} + // ------------------------------------------------------------------------------------------------ // Reads a mesh reference in a node and adds it to the node's mesh list -void ColladaParser::ReadNodeGeometry( Node* pNode) +void ColladaParser::ReadNodeGeometry(Node* pNode) { // referred mesh is given as an attribute of the element - int attrUrl = GetAttribute( "url"); - const char* url = mReader->getAttributeValue( attrUrl); - if( url[0] != '#') - ThrowException( "Unknown reference format"); + int attrUrl = GetAttribute("url"); + const char* url = mReader->getAttributeValue(attrUrl); + if (url[0] != '#') + ThrowException("Unknown reference format"); Collada::MeshInstance instance; - instance.mMeshOrController = url+1; // skipping the leading # + instance.mMeshOrController = url + 1; // skipping the leading # - if( !mReader->isEmptyElement()) + if (!mReader->isEmptyElement()) { // 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) { - if( IsElement( "instance_material")) + if (IsElement("instance_material")) { // read ID of the geometry subgroup and the target material - int attrGroup = GetAttribute( "symbol"); - std::string group = mReader->getAttributeValue( attrGroup); - int attrMaterial = GetAttribute( "target"); - const char* urlMat = mReader->getAttributeValue( attrMaterial); + int attrGroup = GetAttribute("symbol"); + std::string group = mReader->getAttributeValue(attrGroup); + int attrMaterial = GetAttribute("target"); + const char* urlMat = mReader->getAttributeValue(attrMaterial); Collada::SemanticMappingTable s; - if( urlMat[0] == '#') + if (urlMat[0] == '#') urlMat++; s.mMatName = urlMat; // resolve further material details + THIS UGLY AND NASTY semantic mapping stuff - if( !mReader->isEmptyElement()) + if (!mReader->isEmptyElement()) ReadMaterialVertexInputBinding(s); // store the association instance.mMaterials[group] = s; } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { - if( strcmp( mReader->getNodeName(), "instance_geometry") == 0 - || strcmp( mReader->getNodeName(), "instance_controller") == 0) + if (strcmp(mReader->getNodeName(), "instance_geometry") == 0 + || strcmp(mReader->getNodeName(), "instance_controller") == 0) break; } } } // store it - pNode->mMeshes.push_back( instance); + pNode->mMeshes.push_back(instance); } // ------------------------------------------------------------------------------------------------ // Reads the collada scene void ColladaParser::ReadScene() { - if( mReader->isEmptyElement()) + if (mReader->isEmptyElement()) return; - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { - if( IsElement( "instance_visual_scene")) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT) { + if (IsElement("instance_visual_scene")) { // should be the first and only occurrence - if( mRootNode) - ThrowException( "Invalid scene containing multiple root nodes in element"); + if (mRootNode) + ThrowException("Invalid scene containing multiple root nodes in element"); // read the url of the scene to instance. Should be of format "#some_name" - int urlIndex = GetAttribute( "url"); - const char* url = mReader->getAttributeValue( urlIndex); - if( url[0] != '#') - ThrowException( "Unknown reference format in element"); + int urlIndex = GetAttribute("url"); + const char* url = mReader->getAttributeValue(urlIndex); + if (url[0] != '#') + ThrowException("Unknown reference format in element"); // find the referred scene, skip the leading # - NodeLibrary::const_iterator sit = mNodeLibrary.find( url+1); - if( sit == mNodeLibrary.end()) - ThrowException( "Unable to resolve visual_scene reference \"" + std::string(url) + "\" in element."); + NodeLibrary::const_iterator sit = mNodeLibrary.find(url + 1); + if (sit == mNodeLibrary.end()) + ThrowException("Unable to resolve visual_scene reference \"" + std::string(url) + "\" in element."); mRootNode = sit->second; - } else { + } + else { SkipElement(); } } - else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END){ + else if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { break; } } @@ -2976,23 +3170,23 @@ void ColladaParser::ReadScene() // ------------------------------------------------------------------------------------------------ // Aborts the file reading with an exception -AI_WONT_RETURN void ColladaParser::ThrowException( const std::string& pError) const +AI_WONT_RETURN void ColladaParser::ThrowException(const std::string& pError) const { - throw DeadlyImportError( format() << "Collada: " << mFileName << " - " << pError ); + throw DeadlyImportError(format() << "Collada: " << mFileName << " - " << pError); } -void ColladaParser::ReportWarning(const char* msg,...) +void ColladaParser::ReportWarning(const char* msg, ...) { ai_assert(NULL != msg); va_list args; - va_start(args,msg); + va_start(args, msg); char szBuffer[3000]; - const int iLen = vsprintf(szBuffer,msg,args); + const int iLen = vsprintf(szBuffer, msg, args); ai_assert(iLen > 0); va_end(args); - ASSIMP_LOG_WARN_F("Validation warning: ", std::string(szBuffer,iLen)); + ASSIMP_LOG_WARN_F("Validation warning: ", std::string(szBuffer, iLen)); } // ------------------------------------------------------------------------------------------------ @@ -3000,84 +3194,84 @@ void ColladaParser::ReportWarning(const char* msg,...) void ColladaParser::SkipElement() { // nothing to skip if it's an - if( mReader->isEmptyElement()) + if (mReader->isEmptyElement()) return; // reroute - SkipElement( mReader->getNodeName()); + SkipElement(mReader->getNodeName()); } // ------------------------------------------------------------------------------------------------ // Skips all data until the end node of the given element -void ColladaParser::SkipElement( const char* pElement) +void ColladaParser::SkipElement(const char* pElement) { // copy the current node's name because it'a pointer to the reader's internal buffer, // which is going to change with the upcoming parsing std::string element = pElement; - while( mReader->read()) + while (mReader->read()) { - if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) - if( mReader->getNodeName() == element) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END) + if (mReader->getNodeName() == element) break; } } // ------------------------------------------------------------------------------------------------ // Tests for an opening element of the given name, throws an exception if not found -void ColladaParser::TestOpening( const char* pName) +void ColladaParser::TestOpening(const char* pName) { // read element start - if( !mReader->read()) - ThrowException( format() << "Unexpected end of file while beginning of <" << pName << "> element." ); + if (!mReader->read()) + ThrowException(format() << "Unexpected end of file while beginning of <" << pName << "> element."); // whitespace in front is ok, just read again if found - if( mReader->getNodeType() == irr::io::EXN_TEXT) - if( !mReader->read()) - ThrowException( format() << "Unexpected end of file while reading beginning of <" << pName << "> element." ); + if (mReader->getNodeType() == irr::io::EXN_TEXT) + if (!mReader->read()) + ThrowException(format() << "Unexpected end of file while reading beginning of <" << pName << "> element."); - if( mReader->getNodeType() != irr::io::EXN_ELEMENT || strcmp( mReader->getNodeName(), pName) != 0) - ThrowException( format() << "Expected start of <" << pName << "> element." ); + if (mReader->getNodeType() != irr::io::EXN_ELEMENT || strcmp(mReader->getNodeName(), pName) != 0) + ThrowException(format() << "Expected start of <" << pName << "> element."); } // ------------------------------------------------------------------------------------------------ // Tests for the closing tag of the given element, throws an exception if not found -void ColladaParser::TestClosing( const char* pName) +void ColladaParser::TestClosing(const char* pName) { // check if we're already on the closing tag and return right away - if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END && strcmp( mReader->getNodeName(), pName) == 0) + if (mReader->getNodeType() == irr::io::EXN_ELEMENT_END && strcmp(mReader->getNodeName(), pName) == 0) return; // if not, read some more - if( !mReader->read()) - ThrowException( format() << "Unexpected end of file while reading end of <" << pName << "> element." ); + if (!mReader->read()) + ThrowException(format() << "Unexpected end of file while reading end of <" << pName << "> element."); // whitespace in front is ok, just read again if found - if( mReader->getNodeType() == irr::io::EXN_TEXT) - if( !mReader->read()) - ThrowException( format() << "Unexpected end of file while reading end of <" << pName << "> element." ); + if (mReader->getNodeType() == irr::io::EXN_TEXT) + if (!mReader->read()) + ThrowException(format() << "Unexpected end of file while reading end of <" << pName << "> element."); // but this has the be the closing tag, or we're lost - if( mReader->getNodeType() != irr::io::EXN_ELEMENT_END || strcmp( mReader->getNodeName(), pName) != 0) - ThrowException( format() << "Expected end of <" << pName << "> element." ); + if (mReader->getNodeType() != irr::io::EXN_ELEMENT_END || strcmp(mReader->getNodeName(), pName) != 0) + ThrowException(format() << "Expected end of <" << pName << "> element."); } // ------------------------------------------------------------------------------------------------ // Returns the index of the named attribute or -1 if not found. Does not throw, therefore useful for optional attributes -int ColladaParser::GetAttribute( const char* pAttr) const +int ColladaParser::GetAttribute(const char* pAttr) const { - int index = TestAttribute( pAttr); - if( index != -1) + int index = TestAttribute(pAttr); + if (index != -1) return index; // attribute not found -> throw an exception - ThrowException( format() << "Expected attribute \"" << pAttr << "\" for element <" << mReader->getNodeName() << ">." ); + ThrowException(format() << "Expected attribute \"" << pAttr << "\" for element <" << mReader->getNodeName() << ">."); return -1; } // ------------------------------------------------------------------------------------------------ // Tests the present element for the presence of one attribute, returns its index or throws an exception if not found -int ColladaParser::TestAttribute( const char* pAttr) const +int ColladaParser::TestAttribute(const char* pAttr) const { - for( int a = 0; a < mReader->getAttributeCount(); a++) - if( strcmp( mReader->getAttributeName( a), pAttr) == 0) + for (int a = 0; a < mReader->getAttributeCount(); a++) + if (strcmp(mReader->getAttributeName(a), pAttr) == 0) return a; return -1; @@ -3088,8 +3282,8 @@ int ColladaParser::TestAttribute( const char* pAttr) const const char* ColladaParser::GetTextContent() { const char* sz = TestTextContent(); - if(!sz) { - ThrowException( "Invalid contents in element \"n\"."); + if (!sz) { + ThrowException("Invalid contents in element \"n\"."); } return sz; } @@ -3099,85 +3293,85 @@ const char* ColladaParser::GetTextContent() const char* ColladaParser::TestTextContent() { // present node should be the beginning of an element - if( mReader->getNodeType() != irr::io::EXN_ELEMENT || mReader->isEmptyElement()) + if (mReader->getNodeType() != irr::io::EXN_ELEMENT || mReader->isEmptyElement()) return NULL; // read contents of the element - if( !mReader->read() ) + if (!mReader->read()) return NULL; - if( mReader->getNodeType() != irr::io::EXN_TEXT && mReader->getNodeType() != irr::io::EXN_CDATA) + if (mReader->getNodeType() != irr::io::EXN_TEXT && mReader->getNodeType() != irr::io::EXN_CDATA) return NULL; // skip leading whitespace const char* text = mReader->getNodeData(); - SkipSpacesAndLineEnd( &text); + SkipSpacesAndLineEnd(&text); return text; } // ------------------------------------------------------------------------------------------------ // Calculates the resulting transformation fromm all the given transform steps -aiMatrix4x4 ColladaParser::CalculateResultTransform( const std::vector& pTransforms) const +aiMatrix4x4 ColladaParser::CalculateResultTransform(const std::vector& pTransforms) const { aiMatrix4x4 res; - for( std::vector::const_iterator it = pTransforms.begin(); it != pTransforms.end(); ++it) + for (std::vector::const_iterator it = pTransforms.begin(); it != pTransforms.end(); ++it) { const Transform& tf = *it; - switch( tf.mType) + switch (tf.mType) { - case TF_LOOKAT: - { - aiVector3D pos( tf.f[0], tf.f[1], tf.f[2]); - aiVector3D dstPos( tf.f[3], tf.f[4], tf.f[5]); - aiVector3D up = aiVector3D( tf.f[6], tf.f[7], tf.f[8]).Normalize(); - aiVector3D dir = aiVector3D( dstPos - pos).Normalize(); - aiVector3D right = (dir ^ up).Normalize(); + case TF_LOOKAT: + { + aiVector3D pos(tf.f[0], tf.f[1], tf.f[2]); + aiVector3D dstPos(tf.f[3], tf.f[4], tf.f[5]); + aiVector3D up = aiVector3D(tf.f[6], tf.f[7], tf.f[8]).Normalize(); + aiVector3D dir = aiVector3D(dstPos - pos).Normalize(); + aiVector3D right = (dir ^ up).Normalize(); - res *= aiMatrix4x4( - right.x, up.x, -dir.x, pos.x, - right.y, up.y, -dir.y, pos.y, - right.z, up.z, -dir.z, pos.z, - 0, 0, 0, 1); - break; - } - case TF_ROTATE: - { - aiMatrix4x4 rot; - 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]); - aiMatrix4x4::Rotation( angle, axis, rot); - res *= rot; - break; - } - case TF_TRANSLATE: - { - aiMatrix4x4 trans; - aiMatrix4x4::Translation( aiVector3D( tf.f[0], tf.f[1], tf.f[2]), trans); - res *= trans; - break; - } - case TF_SCALE: - { - aiMatrix4x4 scale( tf.f[0], 0.0f, 0.0f, 0.0f, 0.0f, tf.f[1], 0.0f, 0.0f, 0.0f, 0.0f, tf.f[2], 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f); - res *= scale; - break; - } - case TF_SKEW: - // TODO: (thom) - ai_assert( false); - break; - case TF_MATRIX: - { - aiMatrix4x4 mat( tf.f[0], tf.f[1], tf.f[2], tf.f[3], tf.f[4], tf.f[5], tf.f[6], tf.f[7], - tf.f[8], tf.f[9], tf.f[10], tf.f[11], tf.f[12], tf.f[13], tf.f[14], tf.f[15]); - res *= mat; - break; - } - default: - ai_assert( false); - break; + res *= aiMatrix4x4( + right.x, up.x, -dir.x, pos.x, + right.y, up.y, -dir.y, pos.y, + right.z, up.z, -dir.z, pos.z, + 0, 0, 0, 1); + break; + } + case TF_ROTATE: + { + aiMatrix4x4 rot; + 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]); + aiMatrix4x4::Rotation(angle, axis, rot); + res *= rot; + break; + } + case TF_TRANSLATE: + { + aiMatrix4x4 trans; + aiMatrix4x4::Translation(aiVector3D(tf.f[0], tf.f[1], tf.f[2]), trans); + res *= trans; + break; + } + case TF_SCALE: + { + aiMatrix4x4 scale(tf.f[0], 0.0f, 0.0f, 0.0f, 0.0f, tf.f[1], 0.0f, 0.0f, 0.0f, 0.0f, tf.f[2], 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f); + res *= scale; + break; + } + case TF_SKEW: + // TODO: (thom) + ai_assert(false); + break; + case TF_MATRIX: + { + aiMatrix4x4 mat(tf.f[0], tf.f[1], tf.f[2], tf.f[3], tf.f[4], tf.f[5], tf.f[6], tf.f[7], + tf.f[8], tf.f[9], tf.f[10], tf.f[11], tf.f[12], tf.f[13], tf.f[14], tf.f[15]); + res *= mat; + break; + } + default: + ai_assert(false); + break; } } @@ -3186,29 +3380,29 @@ aiMatrix4x4 ColladaParser::CalculateResultTransform( const std::vector StringMetaData; + /** Constructor from XML file */ ColladaParser( IOSystem* pIOHandler, const std::string& pFile); /** Destructor */ ~ColladaParser(); + /** Attempts to read the ZAE manifest and returns the DAE to open */ + static std::string ReadZaeManifest(ZipArchiveIOSystem &zip_archive); + /** Reads the contents of the file */ void ReadContents(); @@ -81,6 +88,15 @@ namespace Assimp /** Reads asset information such as coordinate system information and legal blah */ void ReadAssetInfo(); + /** Reads contributor information such as author and legal blah */ + void ReadContributorInfo(); + + /** Reads generic metadata into provided map */ + void ReadMetaDataItem(StringMetaData &metadata); + + /** Convert underscore_seperated to CamelCase "authoring_tool" becomes "AuthoringTool" */ + static void ToCamelCase(std::string &text); + /** Reads the animation library */ void ReadAnimationLibrary(); @@ -223,6 +239,9 @@ namespace Assimp // Processes bind_vertex_input and bind elements void ReadMaterialVertexInputBinding( Collada::SemanticMappingTable& tbl); + /** Reads embedded textures from a ZAE archive*/ + void ReadEmbeddedTextures(ZipArchiveIOSystem &zip_archive); + protected: /** Aborts the file reading with an exception */ AI_WONT_RETURN void ThrowException( const std::string& pError) const AI_WONT_RETURN_SUFFIX; @@ -343,6 +362,9 @@ namespace Assimp /** Which is the up vector */ enum { UP_X, UP_Y, UP_Z } mUpDirection; + /** Asset metadata (global for scene) */ + StringMetaData mAssetMetaData; + /** Collada file format version */ Collada::FormatVersion mFormat; }; diff --git a/third_party/libassimp/code/Assimp.cpp b/third_party/libassimp/code/Common/Assimp.cpp similarity index 99% rename from third_party/libassimp/code/Assimp.cpp rename to third_party/libassimp/code/Common/Assimp.cpp index 87f436602a..178b2c01d0 100644 --- a/third_party/libassimp/code/Assimp.cpp +++ b/third_party/libassimp/code/Common/Assimp.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -54,7 +54,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include "CInterfaceIOWrapper.h" +#include "CApi/CInterfaceIOWrapper.h" #include "Importer.h" #include "ScenePrivate.h" diff --git a/third_party/libassimp/code/BaseImporter.cpp b/third_party/libassimp/code/Common/BaseImporter.cpp similarity index 95% rename from third_party/libassimp/code/BaseImporter.cpp rename to third_party/libassimp/code/Common/BaseImporter.cpp index f03db189fa..b77bbfe23c 100644 --- a/third_party/libassimp/code/BaseImporter.cpp +++ b/third_party/libassimp/code/Common/BaseImporter.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -76,9 +76,25 @@ BaseImporter::~BaseImporter() { // nothing to do here } +void BaseImporter::UpdateImporterScale( Importer* pImp ) +{ + ai_assert(pImp != nullptr); + ai_assert(importerScale != 0.0); + ai_assert(fileScale != 0.0); + + double activeScale = importerScale * fileScale; + + // Set active scaling + pImp->SetPropertyFloat( AI_CONFIG_APP_SCALE_KEY, static_cast( activeScale) ); + + ASSIMP_LOG_DEBUG_F("UpdateImporterScale scale set: %f", activeScale ); +} + // ------------------------------------------------------------------------------------------------ // Imports the given file and returns the imported data. -aiScene* BaseImporter::ReadFile(const Importer* pImp, const std::string& pFile, IOSystem* pIOHandler) { +aiScene* BaseImporter::ReadFile(Importer* pImp, const std::string& pFile, IOSystem* pIOHandler) { + + m_progress = pImp->GetProgressHandler(); if (nullptr == m_progress) { return nullptr; @@ -100,6 +116,11 @@ aiScene* BaseImporter::ReadFile(const Importer* pImp, const std::string& pFile, { InternReadFile( pFile, sc.get(), &filter); + // Calculate import scale hook - required because pImp not available anywhere else + // passes scale into ScaleProcess + UpdateImporterScale(pImp); + + } catch( const std::exception& err ) { // extract error description m_ErrorText = err.what(); @@ -112,7 +133,7 @@ aiScene* BaseImporter::ReadFile(const Importer* pImp, const std::string& pFile, } // ------------------------------------------------------------------------------------------------ -void BaseImporter::SetupProperties(const Importer* /*pImp*/) +void BaseImporter::SetupProperties(const Importer* pImp) { // the default implementation does nothing } @@ -320,7 +341,11 @@ std::string BaseImporter::GetExtension( const std::string& file ) { return false; } -#include "../contrib/utf8cpp/source/utf8.h" +#ifdef ASSIMP_USE_HUNTER +# include +#else +# include "../contrib/utf8cpp/source/utf8.h" +#endif // ------------------------------------------------------------------------------------------------ // Convert to UTF8 data @@ -584,6 +609,8 @@ aiScene* BatchLoader::GetImport( unsigned int which ) return nullptr; } + + // ------------------------------------------------------------------------------------------------ void BatchLoader::LoadAll() { diff --git a/third_party/libassimp/code/BaseProcess.cpp b/third_party/libassimp/code/Common/BaseProcess.cpp similarity index 97% rename from third_party/libassimp/code/BaseProcess.cpp rename to third_party/libassimp/code/Common/BaseProcess.cpp index 154b586d26..e247be418d 100644 --- a/third_party/libassimp/code/BaseProcess.cpp +++ b/third_party/libassimp/code/Common/BaseProcess.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -89,7 +89,7 @@ void BaseProcess::ExecuteOnScene( Importer* pImp) // and kill the partially imported data delete pImp->Pimpl()->mScene; - pImp->Pimpl()->mScene = NULL; + pImp->Pimpl()->mScene = nullptr; } } diff --git a/third_party/libassimp/code/BaseProcess.h b/third_party/libassimp/code/Common/BaseProcess.h similarity index 99% rename from third_party/libassimp/code/BaseProcess.h rename to third_party/libassimp/code/Common/BaseProcess.h index b09fc732e1..4d5c7a76be 100644 --- a/third_party/libassimp/code/BaseProcess.h +++ b/third_party/libassimp/code/Common/BaseProcess.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/Bitmap.cpp b/third_party/libassimp/code/Common/Bitmap.cpp similarity index 99% rename from third_party/libassimp/code/Bitmap.cpp rename to third_party/libassimp/code/Common/Bitmap.cpp index 903a13fb11..b22b71ea9e 100644 --- a/third_party/libassimp/code/Bitmap.cpp +++ b/third_party/libassimp/code/Common/Bitmap.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/CreateAnimMesh.cpp b/third_party/libassimp/code/Common/CreateAnimMesh.cpp similarity index 96% rename from third_party/libassimp/code/CreateAnimMesh.cpp rename to third_party/libassimp/code/Common/CreateAnimMesh.cpp index 1a052849bb..98b60e5319 100644 --- a/third_party/libassimp/code/CreateAnimMesh.cpp +++ b/third_party/libassimp/code/Common/CreateAnimMesh.cpp @@ -47,10 +47,6 @@ 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]; diff --git a/third_party/libassimp/code/DefaultIOStream.cpp b/third_party/libassimp/code/Common/DefaultIOStream.cpp similarity index 99% rename from third_party/libassimp/code/DefaultIOStream.cpp rename to third_party/libassimp/code/Common/DefaultIOStream.cpp index 3b0a672a70..1c100b6189 100644 --- a/third_party/libassimp/code/DefaultIOStream.cpp +++ b/third_party/libassimp/code/Common/DefaultIOStream.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/DefaultIOSystem.cpp b/third_party/libassimp/code/Common/DefaultIOSystem.cpp similarity index 58% rename from third_party/libassimp/code/DefaultIOSystem.cpp rename to third_party/libassimp/code/Common/DefaultIOSystem.cpp index 58afe475c3..6fdc24dd80 100644 --- a/third_party/libassimp/code/DefaultIOSystem.cpp +++ b/third_party/libassimp/code/Common/DefaultIOSystem.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -61,75 +61,66 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using namespace Assimp; -// maximum path length -// XXX http://insanecoding.blogspot.com/2007/11/pathmax-simply-isnt.html -#ifdef PATH_MAX -# define PATHLIMIT PATH_MAX -#else -# define PATHLIMIT 4096 +#ifdef _WIN32 +static std::wstring Utf8ToWide(const char* in) +{ + int size = MultiByteToWideChar(CP_UTF8, 0, in, -1, nullptr, 0); + // size includes terminating null; std::wstring adds null automatically + std::wstring out(static_cast(size) - 1, L'\0'); + MultiByteToWideChar(CP_UTF8, 0, in, -1, &out[0], size); + return out; +} + +static std::string WideToUtf8(const wchar_t* in) +{ + int size = WideCharToMultiByte(CP_UTF8, 0, in, -1, nullptr, 0, nullptr, nullptr); + // size includes terminating null; std::string adds null automatically + std::string out(static_cast(size) - 1, '\0'); + WideCharToMultiByte(CP_UTF8, 0, in, -1, &out[0], size, nullptr, nullptr); + return out; +} #endif // ------------------------------------------------------------------------------------------------ // Tests for the existence of a file at the given path. -bool DefaultIOSystem::Exists( const char* pFile) const +bool DefaultIOSystem::Exists(const char* pFile) const { #ifdef _WIN32 - wchar_t fileName16[PATHLIMIT]; - - bool isUnicode = IsTextUnicode(pFile, static_cast(strlen(pFile)), NULL) != 0; - if (isUnicode) { - - MultiByteToWideChar(CP_UTF8, MB_PRECOMPOSED, pFile, -1, fileName16, PATHLIMIT); - struct __stat64 filestat; - if (0 != _wstat64(fileName16, &filestat)) { - return false; - } - } else { - FILE* file = ::fopen(pFile, "rb"); - if (!file) - return false; - - ::fclose(file); + struct __stat64 filestat; + if (_wstat64(Utf8ToWide(pFile).c_str(), &filestat) != 0) { + return false; } #else - FILE* file = ::fopen( pFile, "rb"); - if( !file) + FILE* file = ::fopen(pFile, "rb"); + if (!file) return false; - ::fclose( file); + ::fclose(file); #endif return true; } // ------------------------------------------------------------------------------------------------ // Open a new file with a given path. -IOStream* DefaultIOSystem::Open( const char* strFile, const char* strMode) +IOStream* DefaultIOSystem::Open(const char* strFile, const char* strMode) { - ai_assert(NULL != strFile); - ai_assert(NULL != strMode); + ai_assert(strFile != nullptr); + ai_assert(strMode != nullptr); FILE* file; #ifdef _WIN32 - wchar_t fileName16[PATHLIMIT]; - bool isUnicode = IsTextUnicode(strFile, static_cast(strlen(strFile)), NULL) != 0; - if (isUnicode) { - MultiByteToWideChar(CP_UTF8, MB_PRECOMPOSED, strFile, -1, fileName16, PATHLIMIT); - std::string mode8(strMode); - file = ::_wfopen(fileName16, std::wstring(mode8.begin(), mode8.end()).c_str()); - } else { - file = ::fopen(strFile, strMode); - } + file = ::_wfopen(Utf8ToWide(strFile).c_str(), Utf8ToWide(strMode).c_str()); #else file = ::fopen(strFile, strMode); #endif - if (nullptr == file) + if (!file) return nullptr; - return new DefaultIOStream(file, (std::string) strFile); + return new DefaultIOStream(file, strFile); } // ------------------------------------------------------------------------------------------------ // Closes the given file and releases all resources associated with it. -void DefaultIOSystem::Close( IOStream* pFile) +void DefaultIOSystem::Close(IOStream* pFile) { delete pFile; } @@ -147,74 +138,56 @@ char DefaultIOSystem::getOsSeparator() const // ------------------------------------------------------------------------------------------------ // IOSystem default implementation (ComparePaths isn't a pure virtual function) -bool IOSystem::ComparePaths (const char* one, const char* second) const +bool IOSystem::ComparePaths(const char* one, const char* second) const { - return !ASSIMP_stricmp(one,second); + return !ASSIMP_stricmp(one, second); } // ------------------------------------------------------------------------------------------------ // Convert a relative path into an absolute path -inline static void MakeAbsolutePath (const char* in, char* _out) +inline static std::string MakeAbsolutePath(const char* in) { - ai_assert(in && _out); -#if defined( _MSC_VER ) || defined( __MINGW32__ ) - bool isUnicode = IsTextUnicode(in, static_cast(strlen(in)), NULL) != 0; - if (isUnicode) { - wchar_t out16[PATHLIMIT]; - wchar_t in16[PATHLIMIT]; - MultiByteToWideChar(CP_UTF8, MB_PRECOMPOSED, in, -1, out16, PATHLIMIT); - wchar_t* ret = ::_wfullpath(out16, in16, PATHLIMIT); - if (ret) { - WideCharToMultiByte(CP_UTF8, MB_PRECOMPOSED, out16, -1, _out, PATHLIMIT, nullptr, nullptr); - } - if (!ret) { - // preserve the input path, maybe someone else is able to fix - // the path before it is accessed (e.g. our file system filter) - ASSIMP_LOG_WARN_F("Invalid path: ", std::string(in)); - strcpy(_out, in); - } - - } else { - char* ret = :: _fullpath(_out, in, PATHLIMIT); - if (!ret) { - // preserve the input path, maybe someone else is able to fix - // the path before it is accessed (e.g. our file system filter) - ASSIMP_LOG_WARN_F("Invalid path: ", std::string(in)); - strcpy(_out, in); - } + ai_assert(in); + std::string out; +#ifdef _WIN32 + wchar_t* ret = ::_wfullpath(nullptr, Utf8ToWide(in).c_str(), 0); + if (ret) { + out = WideToUtf8(ret); + free(ret); } #else - // use realpath - char* ret = realpath(in, _out); - if(!ret) { + char* ret = realpath(in, nullptr); + if (ret) { + out = ret; + free(ret); + } +#endif + if (!ret) { // preserve the input path, maybe someone else is able to fix // the path before it is accessed (e.g. our file system filter) ASSIMP_LOG_WARN_F("Invalid path: ", std::string(in)); - strcpy(_out,in); + out = in; } -#endif + return out; } // ------------------------------------------------------------------------------------------------ // DefaultIOSystem's more specialized implementation -bool DefaultIOSystem::ComparePaths (const char* one, const char* second) const +bool DefaultIOSystem::ComparePaths(const char* one, const char* second) const { // chances are quite good both paths are formatted identically, // so we can hopefully return here already - if( !ASSIMP_stricmp(one,second) ) + if (!ASSIMP_stricmp(one, second)) return true; - char temp1[PATHLIMIT]; - char temp2[PATHLIMIT]; + std::string temp1 = MakeAbsolutePath(one); + std::string temp2 = MakeAbsolutePath(second); - MakeAbsolutePath (one, temp1); - MakeAbsolutePath (second, temp2); - - return !ASSIMP_stricmp(temp1,temp2); + return !ASSIMP_stricmp(temp1, temp2); } // ------------------------------------------------------------------------------------------------ -std::string DefaultIOSystem::fileName( const std::string &path ) +std::string DefaultIOSystem::fileName(const std::string& path) { std::string ret = path; std::size_t last = ret.find_last_of("\\/"); @@ -223,16 +196,16 @@ std::string DefaultIOSystem::fileName( const std::string &path ) } // ------------------------------------------------------------------------------------------------ -std::string DefaultIOSystem::completeBaseName( const std::string &path ) +std::string DefaultIOSystem::completeBaseName(const std::string& path) { std::string ret = fileName(path); std::size_t pos = ret.find_last_of('.'); - if(pos != ret.npos) ret = ret.substr(0, pos); + if (pos != std::string::npos) ret = ret.substr(0, pos); return ret; } // ------------------------------------------------------------------------------------------------ -std::string DefaultIOSystem::absolutePath( const std::string &path ) +std::string DefaultIOSystem::absolutePath(const std::string& path) { std::string ret = path; std::size_t last = ret.find_last_of("\\/"); @@ -241,5 +214,3 @@ std::string DefaultIOSystem::absolutePath( const std::string &path ) } // ------------------------------------------------------------------------------------------------ - -#undef PATHLIMIT diff --git a/third_party/libassimp/code/DefaultLogger.cpp b/third_party/libassimp/code/Common/DefaultLogger.cpp similarity index 99% rename from third_party/libassimp/code/DefaultLogger.cpp rename to third_party/libassimp/code/Common/DefaultLogger.cpp index 2871a4131f..de3528d2b4 100644 --- a/third_party/libassimp/code/DefaultLogger.cpp +++ b/third_party/libassimp/code/Common/DefaultLogger.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/DefaultProgressHandler.h b/third_party/libassimp/code/Common/DefaultProgressHandler.h similarity index 98% rename from third_party/libassimp/code/DefaultProgressHandler.h rename to third_party/libassimp/code/Common/DefaultProgressHandler.h index 851c17be64..bd2cce00be 100644 --- a/third_party/libassimp/code/DefaultProgressHandler.h +++ b/third_party/libassimp/code/Common/DefaultProgressHandler.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/Exporter.cpp b/third_party/libassimp/code/Common/Exporter.cpp similarity index 94% rename from third_party/libassimp/code/Exporter.cpp rename to third_party/libassimp/code/Common/Exporter.cpp index 0acde75bf6..34d49c472a 100644 --- a/third_party/libassimp/code/Exporter.cpp +++ b/third_party/libassimp/code/Common/Exporter.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -61,15 +61,16 @@ Here we implement only the C++ interface (Assimp::Exporter). #include #include #include - -#include "DefaultProgressHandler.h" -#include "BaseProcess.h" -#include "JoinVerticesProcess.h" -#include "MakeVerboseFormat.h" -#include "ConvertToLHProcess.h" -#include "PretransformVertices.h" #include -#include "ScenePrivate.h" + +#include "Common/DefaultProgressHandler.h" +#include "Common/BaseProcess.h" +#include "Common/ScenePrivate.h" +#include "PostProcessing/CalcTangentsProcess.h" +#include "PostProcessing/MakeVerboseFormat.h" +#include "PostProcessing/JoinVerticesProcess.h" +#include "PostProcessing/ConvertToLHProcess.h" +#include "PostProcessing/PretransformVertices.h" #include @@ -101,6 +102,7 @@ void ExportSceneX3D(const char*, IOSystem*, const aiScene*, const ExportProperti void ExportSceneFBX(const char*, IOSystem*, const aiScene*, const ExportProperties*); void ExportSceneFBXA(const char*, IOSystem*, const aiScene*, const ExportProperties*); void ExportScene3MF( const char*, IOSystem*, const aiScene*, const ExportProperties* ); +void ExportAssimp2Json(const char* , IOSystem*, const aiScene* , const Assimp::ExportProperties*); // ------------------------------------------------------------------------------------------------ // global array of all export formats which Assimp supports in its current build @@ -161,11 +163,11 @@ Exporter::ExportFormatEntry gExporters[] = #endif #ifndef ASSIMP_BUILD_NO_ASSBIN_EXPORTER - Exporter::ExportFormatEntry( "assbin", "Assimp Binary", "assbin" , &ExportSceneAssbin, 0 ), + Exporter::ExportFormatEntry( "assbin", "Assimp Binary File", "assbin" , &ExportSceneAssbin, 0 ), #endif #ifndef ASSIMP_BUILD_NO_ASSXML_EXPORTER - Exporter::ExportFormatEntry( "assxml", "Assxml Document", "assxml" , &ExportSceneAssxml, 0 ), + Exporter::ExportFormatEntry( "assxml", "Assimp XML Document", "assxml" , &ExportSceneAssxml, 0 ), #endif #ifndef ASSIMP_BUILD_NO_X3D_EXPORTER @@ -178,7 +180,11 @@ Exporter::ExportFormatEntry gExporters[] = #endif #ifndef ASSIMP_BUILD_NO_3MF_EXPORTER - Exporter::ExportFormatEntry( "3mf", "The 3MF-File-Format", "3mf", &ExportScene3MF, 0 ) + Exporter::ExportFormatEntry( "3mf", "The 3MF-File-Format", "3mf", &ExportScene3MF, 0 ), +#endif + +#ifndef ASSIMP_BUILD_NO_ASSJSON_EXPORTER + Exporter::ExportFormatEntry( "assjson", "Assimp JSON Document", "json", &ExportAssimp2Json, 0) #endif }; @@ -288,7 +294,7 @@ void Exporter::SetProgressHandler(ProgressHandler* pHandler) { // ------------------------------------------------------------------------------------------------ const aiExportDataBlob* Exporter::ExportToBlob( const aiScene* pScene, const char* pFormatId, - unsigned int, const ExportProperties* /*pProperties*/ ) { + unsigned int pPreprocessing, const ExportProperties* pProperties) { if (pimpl->blob) { delete pimpl->blob; pimpl->blob = nullptr; @@ -298,7 +304,7 @@ const aiExportDataBlob* Exporter::ExportToBlob( const aiScene* pScene, const cha BlobIOSystem* blobio = new BlobIOSystem(); pimpl->mIOSystem = std::shared_ptr( blobio ); - if (AI_SUCCESS != Export(pScene,pFormatId,blobio->GetMagicFileName())) { + if (AI_SUCCESS != Export(pScene,pFormatId,blobio->GetMagicFileName(), pPreprocessing, pProperties)) { pimpl->mIOSystem = old; return nullptr; } @@ -309,34 +315,6 @@ const aiExportDataBlob* Exporter::ExportToBlob( const aiScene* pScene, const cha return pimpl->blob; } -// ------------------------------------------------------------------------------------------------ -bool IsVerboseFormat(const aiMesh* mesh) { - // avoid slow vector specialization - std::vector seen(mesh->mNumVertices,0); - for(unsigned int i = 0; i < mesh->mNumFaces; ++i) { - const aiFace& f = mesh->mFaces[i]; - for(unsigned int j = 0; j < f.mNumIndices; ++j) { - if(++seen[f.mIndices[j]] == 2) { - // found a duplicate index - return false; - } - } - } - - return true; -} - -// ------------------------------------------------------------------------------------------------ -bool IsVerboseFormat(const aiScene* pScene) { - for(unsigned int i = 0; i < pScene->mNumMeshes; ++i) { - if(!IsVerboseFormat(pScene->mMeshes[i])) { - return false; - } - } - - return true; -} - // ------------------------------------------------------------------------------------------------ aiReturn Exporter::Export( const aiScene* pScene, const char* pFormatId, const char* pPath, unsigned int pPreprocessing, const ExportProperties* pProperties) { @@ -346,7 +324,7 @@ aiReturn Exporter::Export( const aiScene* pScene, const char* pFormatId, const c // format. They will likely not be aware that there is a flag in the scene to indicate // this, however. To avoid surprises and bug reports, we check for duplicates in // meshes upfront. - const bool is_verbose_format = !(pScene->mFlags & AI_SCENE_FLAGS_NON_VERBOSE_FORMAT) || IsVerboseFormat(pScene); + const bool is_verbose_format = !(pScene->mFlags & AI_SCENE_FLAGS_NON_VERBOSE_FORMAT) || MakeVerboseFormatProcess::IsVerboseFormat(pScene); pimpl->mProgressHandler->UpdateFileWrite(0, 4); @@ -466,7 +444,10 @@ aiReturn Exporter::Export( const aiScene* pScene, const char* pFormatId, const c } ExportProperties emptyProperties; // Never pass NULL ExportProperties so Exporters don't have to worry. - exp.mExportFunction(pPath,pimpl->mIOSystem.get(),scenecopy.get(), pProperties ? pProperties : &emptyProperties); + ExportProperties* pProp = pProperties ? (ExportProperties*)pProperties : &emptyProperties; + pProp->SetPropertyBool("bJoinIdenticalVertices", must_join_again); + exp.mExportFunction(pPath,pimpl->mIOSystem.get(),scenecopy.get(), pProp); + exp.mExportFunction(pPath,pimpl->mIOSystem.get(),scenecopy.get(), pProp); pimpl->mProgressHandler->UpdateFileWrite(4, 4); } catch (DeadlyExportError& err) { diff --git a/third_party/libassimp/code/FileLogStream.h b/third_party/libassimp/code/Common/FileLogStream.h similarity index 98% rename from third_party/libassimp/code/FileLogStream.h rename to third_party/libassimp/code/Common/FileLogStream.h index 9966091d20..740c503192 100644 --- a/third_party/libassimp/code/FileLogStream.h +++ b/third_party/libassimp/code/Common/FileLogStream.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/FileSystemFilter.h b/third_party/libassimp/code/Common/FileSystemFilter.h similarity index 100% rename from third_party/libassimp/code/FileSystemFilter.h rename to third_party/libassimp/code/Common/FileSystemFilter.h diff --git a/third_party/libassimp/code/IFF.h b/third_party/libassimp/code/Common/IFF.h similarity index 100% rename from third_party/libassimp/code/IFF.h rename to third_party/libassimp/code/Common/IFF.h diff --git a/third_party/libassimp/code/Importer.cpp b/third_party/libassimp/code/Common/Importer.cpp similarity index 98% rename from third_party/libassimp/code/Importer.cpp rename to third_party/libassimp/code/Common/Importer.cpp index fe6df187ce..91b50859a0 100644 --- a/third_party/libassimp/code/Importer.cpp +++ b/third_party/libassimp/code/Common/Importer.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -64,15 +64,15 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ------------------------------------------------------------------------------------------------ // Internal headers // ------------------------------------------------------------------------------------------------ -#include "Importer.h" -#include -#include "BaseProcess.h" +#include "Common/Importer.h" +#include "Common/BaseProcess.h" +#include "Common/DefaultProgressHandler.h" +#include "PostProcessing/ProcessHelper.h" +#include "Common/ScenePreprocessor.h" +#include "Common/ScenePrivate.h" -#include "DefaultProgressHandler.h" +#include #include -#include "ProcessHelper.h" -#include "ScenePreprocessor.h" -#include "ScenePrivate.h" #include #include #include @@ -86,7 +86,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #ifndef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS -# include "ValidateDataStructure.h" +# include "PostProcessing/ValidateDataStructure.h" #endif using namespace Assimp::Profiling; @@ -483,7 +483,7 @@ const aiScene* Importer::ReadFileFromMemory( const void* pBuffer, IOSystem* io = pimpl->mIOHandler; pimpl->mIOHandler = NULL; - SetIOHandler(new MemoryIOSystem((const uint8_t*)pBuffer,pLength)); + SetIOHandler(new MemoryIOSystem((const uint8_t*)pBuffer,pLength,io)); // read the file and recover the previous IOSystem static const size_t BufSize(Importer::MaxLenHint + 28); @@ -590,10 +590,12 @@ const aiScene* Importer::ReadFile( const char* _pFile, unsigned int pFlags) // Find an worker class which can handle the file BaseImporter* imp = NULL; + SetPropertyInteger("importerIndex", -1); for( unsigned int a = 0; a < pimpl->mImporter.size(); a++) { if( pimpl->mImporter[a]->CanRead( pFile, pimpl->mIOHandler, false)) { imp = pimpl->mImporter[a]; + SetPropertyInteger("importerIndex", a); break; } } @@ -606,6 +608,7 @@ const aiScene* Importer::ReadFile( const char* _pFile, unsigned int pFlags) for( unsigned int a = 0; a < pimpl->mImporter.size(); a++) { if( pimpl->mImporter[a]->CanRead( pFile, pimpl->mIOHandler, true)) { imp = pimpl->mImporter[a]; + SetPropertyInteger("importerIndex", a); break; } } diff --git a/third_party/libassimp/code/Importer.h b/third_party/libassimp/code/Common/Importer.h similarity index 99% rename from third_party/libassimp/code/Importer.h rename to third_party/libassimp/code/Common/Importer.h index c6628c4289..a439d99c2f 100644 --- a/third_party/libassimp/code/Importer.h +++ b/third_party/libassimp/code/Common/Importer.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/ImporterRegistry.cpp b/third_party/libassimp/code/Common/ImporterRegistry.cpp similarity index 85% rename from third_party/libassimp/code/ImporterRegistry.cpp rename to third_party/libassimp/code/Common/ImporterRegistry.cpp index d3ae53c7d9..32ac3b4168 100644 --- a/third_party/libassimp/code/ImporterRegistry.cpp +++ b/third_party/libassimp/code/Common/ImporterRegistry.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -56,148 +56,148 @@ corresponding preprocessor flag to selectively disable formats. // (include_new_importers_here) // ------------------------------------------------------------------------------------------------ #ifndef ASSIMP_BUILD_NO_X_IMPORTER -# include "XFileImporter.h" +# include "X/XFileImporter.h" #endif #ifndef ASSIMP_BUILD_NO_AMF_IMPORTER -# include "AMFImporter.hpp" +# include "AMF/AMFImporter.hpp" #endif #ifndef ASSIMP_BUILD_NO_3DS_IMPORTER -# include "3DSLoader.h" +# include "3DS/3DSLoader.h" #endif #ifndef ASSIMP_BUILD_NO_MD3_IMPORTER -# include "MD3Loader.h" +# include "MD3/MD3Loader.h" #endif #ifndef ASSIMP_BUILD_NO_MDL_IMPORTER -# include "MDLLoader.h" +# include "MDL/MDLLoader.h" #endif #ifndef ASSIMP_BUILD_NO_MD2_IMPORTER -# include "MD2Loader.h" +# include "MD2/MD2Loader.h" #endif #ifndef ASSIMP_BUILD_NO_PLY_IMPORTER -# include "PlyLoader.h" +# include "Ply/PlyLoader.h" #endif #ifndef ASSIMP_BUILD_NO_ASE_IMPORTER -# include "ASELoader.h" +# include "ASE/ASELoader.h" #endif #ifndef ASSIMP_BUILD_NO_OBJ_IMPORTER -# include "ObjFileImporter.h" +# include "Obj/ObjFileImporter.h" #endif #ifndef ASSIMP_BUILD_NO_HMP_IMPORTER -# include "HMPLoader.h" +# include "HMP/HMPLoader.h" #endif #ifndef ASSIMP_BUILD_NO_SMD_IMPORTER -# include "SMDLoader.h" +# include "SMD/SMDLoader.h" #endif #ifndef ASSIMP_BUILD_NO_MDC_IMPORTER -# include "MDCLoader.h" +# include "MDC/MDCLoader.h" #endif #ifndef ASSIMP_BUILD_NO_MD5_IMPORTER -# include "MD5Loader.h" +# include "MD5/MD5Loader.h" #endif #ifndef ASSIMP_BUILD_NO_STL_IMPORTER -# include "STLLoader.h" +# include "STL/STLLoader.h" #endif #ifndef ASSIMP_BUILD_NO_LWO_IMPORTER -# include "LWOLoader.h" +# include "LWO/LWOLoader.h" #endif #ifndef ASSIMP_BUILD_NO_DXF_IMPORTER -# include "DXFLoader.h" +# include "DXF/DXFLoader.h" #endif #ifndef ASSIMP_BUILD_NO_NFF_IMPORTER -# include "NFFLoader.h" +# include "NFF/NFFLoader.h" #endif #ifndef ASSIMP_BUILD_NO_RAW_IMPORTER -# include "RawLoader.h" +# include "Raw/RawLoader.h" #endif #ifndef ASSIMP_BUILD_NO_SIB_IMPORTER -# include "SIBImporter.h" +# include "SIB/SIBImporter.h" #endif #ifndef ASSIMP_BUILD_NO_OFF_IMPORTER -# include "OFFLoader.h" +# include "OFF/OFFLoader.h" #endif #ifndef ASSIMP_BUILD_NO_AC_IMPORTER -# include "ACLoader.h" +# include "AC/ACLoader.h" #endif #ifndef ASSIMP_BUILD_NO_BVH_IMPORTER -# include "BVHLoader.h" +# include "BVH/BVHLoader.h" #endif #ifndef ASSIMP_BUILD_NO_IRRMESH_IMPORTER -# include "IRRMeshLoader.h" +# include "Irr/IRRMeshLoader.h" #endif #ifndef ASSIMP_BUILD_NO_IRR_IMPORTER -# include "IRRLoader.h" +# include "Irr/IRRLoader.h" #endif #ifndef ASSIMP_BUILD_NO_Q3D_IMPORTER -# include "Q3DLoader.h" +# include "Q3D/Q3DLoader.h" #endif #ifndef ASSIMP_BUILD_NO_B3D_IMPORTER -# include "B3DImporter.h" +# include "B3D/B3DImporter.h" #endif #ifndef ASSIMP_BUILD_NO_COLLADA_IMPORTER -# include "ColladaLoader.h" +# include "Collada/ColladaLoader.h" #endif #ifndef ASSIMP_BUILD_NO_TERRAGEN_IMPORTER -# include "TerragenLoader.h" +# include "Terragen/TerragenLoader.h" #endif #ifndef ASSIMP_BUILD_NO_CSM_IMPORTER -# include "CSMLoader.h" +# include "CSM/CSMLoader.h" #endif #ifndef ASSIMP_BUILD_NO_3D_IMPORTER -# include "UnrealLoader.h" +# include "Unreal/UnrealLoader.h" #endif #ifndef ASSIMP_BUILD_NO_LWS_IMPORTER -# include "LWSLoader.h" +# include "LWS/LWSLoader.h" #endif #ifndef ASSIMP_BUILD_NO_OGRE_IMPORTER -# include "OgreImporter.h" +# include "Ogre/OgreImporter.h" #endif #ifndef ASSIMP_BUILD_NO_OPENGEX_IMPORTER -# include "OpenGEXImporter.h" +# include "OpenGEX/OpenGEXImporter.h" #endif #ifndef ASSIMP_BUILD_NO_MS3D_IMPORTER -# include "MS3DLoader.h" +# include "MS3D/MS3DLoader.h" #endif #ifndef ASSIMP_BUILD_NO_COB_IMPORTER -# include "COBLoader.h" +# include "COB/COBLoader.h" #endif #ifndef ASSIMP_BUILD_NO_BLEND_IMPORTER -# include "BlenderLoader.h" +# include "Blender/BlenderLoader.h" #endif #ifndef ASSIMP_BUILD_NO_Q3BSP_IMPORTER -# include "Q3BSPFileImporter.h" +# include "Q3BSP/Q3BSPFileImporter.h" #endif #ifndef ASSIMP_BUILD_NO_NDO_IMPORTER -# include "NDOLoader.h" +# include "NDO/NDOLoader.h" #endif #ifndef ASSIMP_BUILD_NO_IFC_IMPORTER # include "Importer/IFC/IFCLoader.h" #endif #ifndef ASSIMP_BUILD_NO_XGL_IMPORTER -# include "XGLLoader.h" +# include "XGL/XGLLoader.h" #endif #ifndef ASSIMP_BUILD_NO_FBX_IMPORTER -# include "FBXImporter.h" +# include "FBX/FBXImporter.h" #endif #ifndef ASSIMP_BUILD_NO_ASSBIN_IMPORTER -# include "AssbinLoader.h" +# include "Assbin/AssbinLoader.h" #endif #ifndef ASSIMP_BUILD_NO_GLTF_IMPORTER -# include "glTFImporter.h" -# include "glTF2Importer.h" +# include "glTF/glTFImporter.h" +# include "glTF2/glTF2Importer.h" #endif #ifndef ASSIMP_BUILD_NO_C4D_IMPORTER -# include "C4DImporter.h" +# include "C4D/C4DImporter.h" #endif #ifndef ASSIMP_BUILD_NO_3MF_IMPORTER -# include "D3MFImporter.h" +# include "3MF/D3MFImporter.h" #endif #ifndef ASSIMP_BUILD_NO_X3D_IMPORTER -# include "X3DImporter.hpp" +# include "X3D/X3DImporter.hpp" #endif #ifndef ASSIMP_BUILD_NO_MMD_IMPORTER -# include "MMDImporter.h" +# include "MMD/MMDImporter.h" #endif -#ifndef ASSIMP_BUILD_NO_STEPFILE_IMPORTER +#ifndef ASSIMP_BUILD_NO_STEP_IMPORTER # include "Importer/StepFile/StepFileImporter.h" #endif @@ -355,7 +355,7 @@ void GetImporterInstanceList(std::vector< BaseImporter* >& out) #ifndef ASSIMP_BUILD_NO_MMD_IMPORTER out.push_back( new MMDImporter() ); #endif -#ifndef ASSIMP_BUILD_NO_STEPFILE_IMPORTER +#ifndef ASSIMP_BUILD_NO_STEP_IMPORTER out.push_back(new StepFile::StepFileImporter()); #endif } @@ -364,7 +364,7 @@ void GetImporterInstanceList(std::vector< BaseImporter* >& out) void DeleteImporterInstanceList(std::vector< BaseImporter* >& deleteList){ for(size_t i= 0; i& out) #ifndef ASSIMP_BUILD_NO_TRANSFORMTEXCOORDS_PROCESS out.push_back( new TextureTransformStep()); #endif +#if (!defined ASSIMP_BUILD_NO_GLOBALSCALE_PROCESS) + out.push_back( new ScaleProcess()); +#endif #if (!defined ASSIMP_BUILD_NO_PRETRANSFORMVERTICES_PROCESS) out.push_back( new PretransformVertices()); #endif @@ -208,9 +215,6 @@ void GetPostProcessingStepInstanceList(std::vector< BaseProcess* >& out) #endif #if (!defined ASSIMP_BUILD_NO_GENFACENORMALS_PROCESS) out.push_back( new GenFaceNormalsProcess()); -#endif -#if (!defined ASSIMP_BUILD_NO_GLOBALSCALE_PROCESS) - out.push_back( new ScaleProcess()); #endif // ......................................................................... // DON'T change the order of these five .. @@ -246,6 +250,9 @@ void GetPostProcessingStepInstanceList(std::vector< BaseProcess* >& out) #if (!defined ASSIMP_BUILD_NO_IMPROVECACHELOCALITY_PROCESS) out.push_back( new ImproveCacheLocalityProcess()); #endif +#if (!defined ASSIMP_BUILD_NO_GENBOUNDINGBOXES_PROCESS) + out.push_back(new GenBoundingBoxesProcess); +#endif } } diff --git a/third_party/libassimp/code/RemoveComments.cpp b/third_party/libassimp/code/Common/RemoveComments.cpp similarity index 99% rename from third_party/libassimp/code/RemoveComments.cpp rename to third_party/libassimp/code/Common/RemoveComments.cpp index 3ba3c60be0..91700a7699 100644 --- a/third_party/libassimp/code/RemoveComments.cpp +++ b/third_party/libassimp/code/Common/RemoveComments.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/SGSpatialSort.cpp b/third_party/libassimp/code/Common/SGSpatialSort.cpp similarity index 99% rename from third_party/libassimp/code/SGSpatialSort.cpp rename to third_party/libassimp/code/Common/SGSpatialSort.cpp index d74c57ed5b..120070b0aa 100644 --- a/third_party/libassimp/code/SGSpatialSort.cpp +++ b/third_party/libassimp/code/Common/SGSpatialSort.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/SceneCombiner.cpp b/third_party/libassimp/code/Common/SceneCombiner.cpp similarity index 97% rename from third_party/libassimp/code/SceneCombiner.cpp rename to third_party/libassimp/code/Common/SceneCombiner.cpp index 883447372f..4e6bc5b475 100644 --- a/third_party/libassimp/code/SceneCombiner.cpp +++ b/third_party/libassimp/code/Common/SceneCombiner.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -738,7 +738,11 @@ void SceneCombiner::MergeBones(aiMesh* out,std::vector::const_iterator // And copy the final weights - adjust the vertex IDs by the // face index offset of the corresponding mesh. - for (std::vector< BoneSrcIndex >::const_iterator wmit = (*boneIt).pSrcBones.begin(); wmit != wend; ++wmit) { + for (std::vector< BoneSrcIndex >::const_iterator wmit = (*boneIt).pSrcBones.begin(); wmit != (*boneIt).pSrcBones.end(); ++wmit) { + if (wmit == wend) { + break; + } + aiBone* pip = (*wmit).first; for (unsigned int mp = 0; mp < pip->mNumWeights;++mp,++avw) { const aiVertexWeight& vfi = pip->mWeights[mp]; @@ -1087,6 +1091,35 @@ void SceneCombiner::Copy( aiMesh** _dest, const aiMesh* src ) { aiFace& f = dest->mFaces[i]; GetArrayCopy(f.mIndices,f.mNumIndices); } + + // make a deep copy of all blend shapes + CopyPtrArray(dest->mAnimMeshes, dest->mAnimMeshes, dest->mNumAnimMeshes); +} + +// ------------------------------------------------------------------------------------------------ +void SceneCombiner::Copy(aiAnimMesh** _dest, const aiAnimMesh* src) { + if (nullptr == _dest || nullptr == src) { + return; + } + + aiAnimMesh* dest = *_dest = new aiAnimMesh(); + + // get a flat copy + ::memcpy(dest, src, sizeof(aiAnimMesh)); + + // and reallocate all arrays + GetArrayCopy(dest->mVertices, dest->mNumVertices); + GetArrayCopy(dest->mNormals, dest->mNumVertices); + GetArrayCopy(dest->mTangents, dest->mNumVertices); + GetArrayCopy(dest->mBitangents, dest->mNumVertices); + + unsigned int n = 0; + while (dest->HasTextureCoords(n)) + GetArrayCopy(dest->mTextureCoords[n++], dest->mNumVertices); + + n = 0; + while (dest->HasVertexColors(n)) + GetArrayCopy(dest->mColors[n++], dest->mNumVertices); } // ------------------------------------------------------------------------------------------------ diff --git a/third_party/libassimp/code/ScenePreprocessor.cpp b/third_party/libassimp/code/Common/ScenePreprocessor.cpp similarity index 99% rename from third_party/libassimp/code/ScenePreprocessor.cpp rename to third_party/libassimp/code/Common/ScenePreprocessor.cpp index 1228ab2c2f..432a3d7666 100644 --- a/third_party/libassimp/code/ScenePreprocessor.cpp +++ b/third_party/libassimp/code/Common/ScenePreprocessor.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/ScenePreprocessor.h b/third_party/libassimp/code/Common/ScenePreprocessor.h similarity index 99% rename from third_party/libassimp/code/ScenePreprocessor.h rename to third_party/libassimp/code/Common/ScenePreprocessor.h index 3900a237bd..3f4c8d7c3f 100644 --- a/third_party/libassimp/code/ScenePreprocessor.h +++ b/third_party/libassimp/code/Common/ScenePreprocessor.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/ScenePrivate.h b/third_party/libassimp/code/Common/ScenePrivate.h similarity index 98% rename from third_party/libassimp/code/ScenePrivate.h rename to third_party/libassimp/code/Common/ScenePrivate.h index 775b9cb52d..f336aafc9a 100644 --- a/third_party/libassimp/code/ScenePrivate.h +++ b/third_party/libassimp/code/Common/ScenePrivate.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/SkeletonMeshBuilder.cpp b/third_party/libassimp/code/Common/SkeletonMeshBuilder.cpp similarity index 99% rename from third_party/libassimp/code/SkeletonMeshBuilder.cpp rename to third_party/libassimp/code/Common/SkeletonMeshBuilder.cpp index ecfe8586fa..06cfe034e9 100644 --- a/third_party/libassimp/code/SkeletonMeshBuilder.cpp +++ b/third_party/libassimp/code/Common/SkeletonMeshBuilder.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/SpatialSort.cpp b/third_party/libassimp/code/Common/SpatialSort.cpp similarity index 99% rename from third_party/libassimp/code/SpatialSort.cpp rename to third_party/libassimp/code/Common/SpatialSort.cpp index b0ab6e412d..a4f3a4e4b8 100644 --- a/third_party/libassimp/code/SpatialSort.cpp +++ b/third_party/libassimp/code/Common/SpatialSort.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/SplitByBoneCountProcess.cpp b/third_party/libassimp/code/Common/SplitByBoneCountProcess.cpp similarity index 99% rename from third_party/libassimp/code/SplitByBoneCountProcess.cpp rename to third_party/libassimp/code/Common/SplitByBoneCountProcess.cpp index 6faf110869..2ef66a9afc 100644 --- a/third_party/libassimp/code/SplitByBoneCountProcess.cpp +++ b/third_party/libassimp/code/Common/SplitByBoneCountProcess.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/SplitByBoneCountProcess.h b/third_party/libassimp/code/Common/SplitByBoneCountProcess.h similarity index 99% rename from third_party/libassimp/code/SplitByBoneCountProcess.h rename to third_party/libassimp/code/Common/SplitByBoneCountProcess.h index b46dd6b0fb..6c904a9df4 100644 --- a/third_party/libassimp/code/SplitByBoneCountProcess.h +++ b/third_party/libassimp/code/Common/SplitByBoneCountProcess.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/StandardShapes.cpp b/third_party/libassimp/code/Common/StandardShapes.cpp similarity index 95% rename from third_party/libassimp/code/StandardShapes.cpp rename to third_party/libassimp/code/Common/StandardShapes.cpp index 7d2319401f..2e5100130f 100644 --- a/third_party/libassimp/code/StandardShapes.cpp +++ b/third_party/libassimp/code/Common/StandardShapes.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -127,35 +127,35 @@ aiMesh* StandardShapes::MakeMesh(const std::vector& positions, // Determine which kinds of primitives the mesh consists of aiMesh* out = new aiMesh(); - switch (numIndices) - { - case 1: - out->mPrimitiveTypes = aiPrimitiveType_POINT; - break; - case 2: - out->mPrimitiveTypes = aiPrimitiveType_LINE; - break; - case 3: - out->mPrimitiveTypes = aiPrimitiveType_TRIANGLE; - break; - default: - out->mPrimitiveTypes = aiPrimitiveType_POLYGON; - break; + switch (numIndices) { + case 1: + out->mPrimitiveTypes = aiPrimitiveType_POINT; + break; + case 2: + out->mPrimitiveTypes = aiPrimitiveType_LINE; + break; + case 3: + out->mPrimitiveTypes = aiPrimitiveType_TRIANGLE; + break; + default: + out->mPrimitiveTypes = aiPrimitiveType_POLYGON; + break; }; out->mNumFaces = (unsigned int)positions.size() / numIndices; out->mFaces = new aiFace[out->mNumFaces]; - for (unsigned int i = 0, a = 0; i < out->mNumFaces;++i) - { + for (unsigned int i = 0, a = 0; i < out->mNumFaces;++i) { aiFace& f = out->mFaces[i]; f.mNumIndices = numIndices; f.mIndices = new unsigned int[numIndices]; - for (unsigned int i = 0; i < numIndices;++i,++a) - f.mIndices[i] = a; + for (unsigned int j = 0; i < numIndices; ++i, ++a) { + f.mIndices[j] = a; + } } out->mNumVertices = (unsigned int)positions.size(); out->mVertices = new aiVector3D[out->mNumVertices]; ::memcpy(out->mVertices,&positions[0],out->mNumVertices*sizeof(aiVector3D)); + return out; } @@ -466,8 +466,8 @@ void StandardShapes::MakeCone(ai_real height,ai_real radius1, // Need to flip face order? if ( SIZE_MAX != old ) { - for (size_t s = old; s < positions.size();s += 3) { - std::swap(positions[s],positions[s+1]); + for (size_t p = old; p < positions.size();p += 3) { + std::swap(positions[p],positions[p+1]); } } } diff --git a/third_party/libassimp/code/StdOStreamLogStream.h b/third_party/libassimp/code/Common/StdOStreamLogStream.h similarity index 98% rename from third_party/libassimp/code/StdOStreamLogStream.h rename to third_party/libassimp/code/Common/StdOStreamLogStream.h index 43b8d7de2e..893e261a2b 100644 --- a/third_party/libassimp/code/StdOStreamLogStream.h +++ b/third_party/libassimp/code/Common/StdOStreamLogStream.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/Subdivision.cpp b/third_party/libassimp/code/Common/Subdivision.cpp similarity index 99% rename from third_party/libassimp/code/Subdivision.cpp rename to third_party/libassimp/code/Common/Subdivision.cpp index 2f2f09596a..60c54939f5 100644 --- a/third_party/libassimp/code/Subdivision.cpp +++ b/third_party/libassimp/code/Common/Subdivision.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -43,9 +43,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include -#include "ProcessHelper.h" #include #include + +#include "PostProcessing/ProcessHelper.h" + #include using namespace Assimp; @@ -56,8 +58,7 @@ void mydummy() {} * implementation is basing on recursive refinement. Directly evaluating the result is also * possible and much quicker, but it depends on lengthy matrix lookup tables. */ // ------------------------------------------------------------------------------------------------ -class CatmullClarkSubdivider : public Subdivider -{ +class CatmullClarkSubdivider : public Subdivider { public: void Subdivide (aiMesh* mesh, aiMesh*& out, unsigned int num, bool discard_input); void Subdivide (aiMesh** smesh, size_t nmesh, diff --git a/third_party/libassimp/code/TargetAnimation.cpp b/third_party/libassimp/code/Common/TargetAnimation.cpp similarity index 99% rename from third_party/libassimp/code/TargetAnimation.cpp rename to third_party/libassimp/code/Common/TargetAnimation.cpp index 2834b1f108..b8062499ff 100644 --- a/third_party/libassimp/code/TargetAnimation.cpp +++ b/third_party/libassimp/code/Common/TargetAnimation.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/TargetAnimation.h b/third_party/libassimp/code/Common/TargetAnimation.h similarity index 99% rename from third_party/libassimp/code/TargetAnimation.h rename to third_party/libassimp/code/Common/TargetAnimation.h index bb37e6008d..91634ab5aa 100644 --- a/third_party/libassimp/code/TargetAnimation.h +++ b/third_party/libassimp/code/Common/TargetAnimation.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/Version.cpp b/third_party/libassimp/code/Common/Version.cpp similarity index 96% rename from third_party/libassimp/code/Version.cpp rename to third_party/libassimp/code/Common/Version.cpp index b823abd685..5f72fd3197 100644 --- a/third_party/libassimp/code/Version.cpp +++ b/third_party/libassimp/code/Common/Version.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -46,8 +46,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include "ScenePrivate.h" -static const unsigned int MajorVersion = 4; -static const unsigned int MinorVersion = 1; +static const unsigned int MajorVersion = 5; +static const unsigned int MinorVersion = 0; // -------------------------------------------------------------------------------- // Legal information string - don't remove this. @@ -56,9 +56,9 @@ static const char* LEGAL_INFORMATION = "Open Asset Import Library (Assimp).\n" "A free C/C++ library to import various 3D file formats into applications\n\n" -"(c) 2008-2017, assimp team\n" +"(c) 2008-2020, assimp team\n" "License under the terms and conditions of the 3-clause BSD license\n" -"http://assimp.sourceforge.net\n" +"https://github.com/assimp/assimp\n" ; // ------------------------------------------------------------------------------------------------ diff --git a/third_party/libassimp/code/VertexTriangleAdjacency.cpp b/third_party/libassimp/code/Common/VertexTriangleAdjacency.cpp similarity index 99% rename from third_party/libassimp/code/VertexTriangleAdjacency.cpp rename to third_party/libassimp/code/Common/VertexTriangleAdjacency.cpp index b41fd029d3..7cfd1a3505 100644 --- a/third_party/libassimp/code/VertexTriangleAdjacency.cpp +++ b/third_party/libassimp/code/Common/VertexTriangleAdjacency.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/VertexTriangleAdjacency.h b/third_party/libassimp/code/Common/VertexTriangleAdjacency.h similarity index 99% rename from third_party/libassimp/code/VertexTriangleAdjacency.h rename to third_party/libassimp/code/Common/VertexTriangleAdjacency.h index 23624a5be6..f3be47612d 100644 --- a/third_party/libassimp/code/VertexTriangleAdjacency.h +++ b/third_party/libassimp/code/Common/VertexTriangleAdjacency.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/Win32DebugLogStream.h b/third_party/libassimp/code/Common/Win32DebugLogStream.h similarity index 98% rename from third_party/libassimp/code/Win32DebugLogStream.h rename to third_party/libassimp/code/Common/Win32DebugLogStream.h index 7bbe8002ae..a6063a261e 100644 --- a/third_party/libassimp/code/Win32DebugLogStream.h +++ b/third_party/libassimp/code/Common/Win32DebugLogStream.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/Common/ZipArchiveIOSystem.cpp b/third_party/libassimp/code/Common/ZipArchiveIOSystem.cpp new file mode 100644 index 0000000000..7c37a05f94 --- /dev/null +++ b/third_party/libassimp/code/Common/ZipArchiveIOSystem.cpp @@ -0,0 +1,539 @@ +/* +Open Asset Import Library (assimp) +---------------------------------------------------------------------- + +Copyright (c) 2006-2019, 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 ZipArchiveIOSystem.cpp + * @brief Zip File I/O implementation for #Importer + */ + +#include +#include + +#include + +#include +#include + +#ifdef ASSIMP_USE_HUNTER +# include +#else +# include +#endif + +namespace Assimp { + // ---------------------------------------------------------------- + // Wraps an existing Assimp::IOSystem for unzip + class IOSystem2Unzip { + public: + static voidpf open(voidpf opaque, const char* filename, int mode); + static uLong read(voidpf opaque, voidpf stream, void* buf, uLong size); + static uLong write(voidpf opaque, voidpf stream, const void* buf, uLong size); + static long tell(voidpf opaque, voidpf stream); + static long seek(voidpf opaque, voidpf stream, uLong offset, int origin); + static int close(voidpf opaque, voidpf stream); + static int testerror(voidpf opaque, voidpf stream); + static zlib_filefunc_def get(IOSystem* pIOHandler); + }; + + voidpf IOSystem2Unzip::open(voidpf opaque, const char* filename, int mode) { + IOSystem* io_system = reinterpret_cast(opaque); + + const char* mode_fopen = nullptr; + if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER) == ZLIB_FILEFUNC_MODE_READ) { + mode_fopen = "rb"; + } + else { + if (mode & ZLIB_FILEFUNC_MODE_EXISTING) { + mode_fopen = "r+b"; + } + else { + if (mode & ZLIB_FILEFUNC_MODE_CREATE) { + mode_fopen = "wb"; + } + } + } + + return (voidpf)io_system->Open(filename, mode_fopen); + } + + uLong IOSystem2Unzip::read(voidpf /*opaque*/, voidpf stream, void* buf, uLong size) { + IOStream* io_stream = (IOStream*)stream; + + return static_cast(io_stream->Read(buf, 1, size)); + } + + uLong IOSystem2Unzip::write(voidpf /*opaque*/, voidpf stream, const void* buf, uLong size) { + IOStream* io_stream = (IOStream*)stream; + + return static_cast(io_stream->Write(buf, 1, size)); + } + + long IOSystem2Unzip::tell(voidpf /*opaque*/, voidpf stream) { + IOStream* io_stream = (IOStream*)stream; + + return static_cast(io_stream->Tell()); + } + + long IOSystem2Unzip::seek(voidpf /*opaque*/, voidpf stream, uLong offset, int origin) { + IOStream* io_stream = (IOStream*)stream; + + aiOrigin assimp_origin; + switch (origin) { + default: + case ZLIB_FILEFUNC_SEEK_CUR: + assimp_origin = aiOrigin_CUR; + break; + case ZLIB_FILEFUNC_SEEK_END: + assimp_origin = aiOrigin_END; + break; + case ZLIB_FILEFUNC_SEEK_SET: + assimp_origin = aiOrigin_SET; + break; + } + + return (io_stream->Seek(offset, assimp_origin) == aiReturn_SUCCESS ? 0 : -1); + } + + int IOSystem2Unzip::close(voidpf opaque, voidpf stream) { + IOSystem* io_system = (IOSystem*)opaque; + IOStream* io_stream = (IOStream*)stream; + + io_system->Close(io_stream); + + return 0; + } + + int IOSystem2Unzip::testerror(voidpf /*opaque*/, voidpf /*stream*/) { + return 0; + } + + zlib_filefunc_def IOSystem2Unzip::get(IOSystem* pIOHandler) { + zlib_filefunc_def mapping; + +#ifdef ASSIMP_USE_HUNTER + mapping.zopen_file = (open_file_func)open; + mapping.zread_file = (read_file_func)read; + mapping.zwrite_file = (write_file_func)write; + mapping.ztell_file = (tell_file_func)tell; + mapping.zseek_file = (seek_file_func)seek; + mapping.zclose_file = (close_file_func)close; + mapping.zerror_file = (error_file_func)testerror; +#else + mapping.zopen_file = open; + mapping.zread_file = read; + mapping.zwrite_file = write; + mapping.ztell_file = tell; + mapping.zseek_file = seek; + mapping.zclose_file = close; + mapping.zerror_file = testerror; +#endif + mapping.opaque = reinterpret_cast(pIOHandler); + + return mapping; + } + + // ---------------------------------------------------------------- + // A read-only file inside a ZIP + + class ZipFile : public IOStream { + friend class ZipFileInfo; + explicit ZipFile(size_t size); + public: + virtual ~ZipFile(); + + // IOStream interface + size_t Read(void* pvBuffer, size_t pSize, size_t pCount) override; + size_t Write(const void* /*pvBuffer*/, size_t /*pSize*/, size_t /*pCount*/) override { return 0; } + size_t FileSize() const override; + aiReturn Seek(size_t pOffset, aiOrigin pOrigin) override; + size_t Tell() const override; + void Flush() override {} + + private: + size_t m_Size = 0; + size_t m_SeekPtr = 0; + std::unique_ptr m_Buffer; + }; + + + // ---------------------------------------------------------------- + // Info about a read-only file inside a ZIP + class ZipFileInfo + { + public: + explicit ZipFileInfo(unzFile zip_handle, size_t size); + + // Allocate and Extract data from the ZIP + ZipFile * Extract(unzFile zip_handle) const; + + private: + size_t m_Size = 0; + unz_file_pos_s m_ZipFilePos; + }; + + ZipFileInfo::ZipFileInfo(unzFile zip_handle, size_t size) + : m_Size(size) { + ai_assert(m_Size != 0); + // Workaround for MSVC 2013 - C2797 + m_ZipFilePos.num_of_file = 0; + m_ZipFilePos.pos_in_zip_directory = 0; + unzGetFilePos(zip_handle, &(m_ZipFilePos)); + } + + ZipFile * ZipFileInfo::Extract(unzFile zip_handle) const { + // Find in the ZIP. This cannot fail + unz_file_pos_s *filepos = const_cast(&(m_ZipFilePos)); + if (unzGoToFilePos(zip_handle, filepos) != UNZ_OK) + return nullptr; + + if (unzOpenCurrentFile(zip_handle) != UNZ_OK) + return nullptr; + + ZipFile *zip_file = new ZipFile(m_Size); + + if (unzReadCurrentFile(zip_handle, zip_file->m_Buffer.get(), static_cast(m_Size)) != static_cast(m_Size)) + { + // Failed, release the memory + delete zip_file; + zip_file = nullptr; + } + + ai_assert(unzCloseCurrentFile(zip_handle) == UNZ_OK); + return zip_file; + } + + ZipFile::ZipFile(size_t size) + : m_Size(size) { + ai_assert(m_Size != 0); + m_Buffer = std::unique_ptr(new uint8_t[m_Size]); + } + + ZipFile::~ZipFile() { + } + + size_t ZipFile::Read(void* pvBuffer, size_t pSize, size_t pCount) { + // Should be impossible + ai_assert(m_Buffer != nullptr); + ai_assert(NULL != pvBuffer && 0 != pSize && 0 != pCount); + + // Clip down to file size + size_t byteSize = pSize * pCount; + if ((byteSize + m_SeekPtr) > m_Size) + { + pCount = (m_Size - m_SeekPtr) / pSize; + byteSize = pSize * pCount; + if (byteSize == 0) + return 0; + } + + std::memcpy(pvBuffer, m_Buffer.get() + m_SeekPtr, byteSize); + + m_SeekPtr += byteSize; + + return pCount; + } + + size_t ZipFile::FileSize() const { + return m_Size; + } + + aiReturn ZipFile::Seek(size_t pOffset, aiOrigin pOrigin) { + switch (pOrigin) + { + case aiOrigin_SET: { + if (pOffset > m_Size) return aiReturn_FAILURE; + m_SeekPtr = pOffset; + return aiReturn_SUCCESS; + } + + case aiOrigin_CUR: { + if ((pOffset + m_SeekPtr) > m_Size) return aiReturn_FAILURE; + m_SeekPtr += pOffset; + return aiReturn_SUCCESS; + } + + case aiOrigin_END: { + if (pOffset > m_Size) return aiReturn_FAILURE; + m_SeekPtr = m_Size - pOffset; + return aiReturn_SUCCESS; + } + default:; + } + + return aiReturn_FAILURE; + } + + size_t ZipFile::Tell() const { + return m_SeekPtr; + } + + // ---------------------------------------------------------------- + // pImpl of the Zip Archive IO + class ZipArchiveIOSystem::Implement { + public: + static const unsigned int FileNameSize = 256; + + Implement(IOSystem* pIOHandler, const char* pFilename, const char* pMode); + ~Implement(); + + bool isOpen() const; + void getFileList(std::vector& rFileList); + void getFileListExtension(std::vector& rFileList, const std::string& extension); + bool Exists(std::string& filename); + IOStream* OpenFile(std::string& filename); + + static void SimplifyFilename(std::string& filename); + + private: + void MapArchive(); + + private: + typedef std::map ZipFileInfoMap; + + unzFile m_ZipFileHandle = nullptr; + ZipFileInfoMap m_ArchiveMap; + }; + + ZipArchiveIOSystem::Implement::Implement(IOSystem* pIOHandler, const char* pFilename, const char* pMode) { + ai_assert(strcmp(pMode, "r") == 0); + ai_assert(pFilename != nullptr); + if (pFilename[0] == 0) + return; + + zlib_filefunc_def mapping = IOSystem2Unzip::get(pIOHandler); + m_ZipFileHandle = unzOpen2(pFilename, &mapping); + } + + ZipArchiveIOSystem::Implement::~Implement() { + m_ArchiveMap.clear(); + + if (m_ZipFileHandle != nullptr) { + unzClose(m_ZipFileHandle); + m_ZipFileHandle = nullptr; + } + } + + void ZipArchiveIOSystem::Implement::MapArchive() { + if (m_ZipFileHandle == nullptr) + return; + + if (!m_ArchiveMap.empty()) + return; + + // At first ensure file is already open + if (unzGoToFirstFile(m_ZipFileHandle) != UNZ_OK) + return; + + // Loop over all files + do { + char filename[FileNameSize]; + unz_file_info fileInfo; + + if (unzGetCurrentFileInfo(m_ZipFileHandle, &fileInfo, filename, FileNameSize, nullptr, 0, nullptr, 0) == UNZ_OK) { + if (fileInfo.uncompressed_size != 0) { + std::string filename_string(filename, fileInfo.size_filename); + SimplifyFilename(filename_string); + m_ArchiveMap.emplace(filename_string, ZipFileInfo(m_ZipFileHandle, fileInfo.uncompressed_size)); + } + } + } while (unzGoToNextFile(m_ZipFileHandle) != UNZ_END_OF_LIST_OF_FILE); + } + + bool ZipArchiveIOSystem::Implement::isOpen() const { + return (m_ZipFileHandle != nullptr); + } + + void ZipArchiveIOSystem::Implement::getFileList(std::vector& rFileList) { + MapArchive(); + rFileList.clear(); + + for (const auto &file : m_ArchiveMap) { + rFileList.push_back(file.first); + } + } + + void ZipArchiveIOSystem::Implement::getFileListExtension(std::vector& rFileList, const std::string& extension) { + MapArchive(); + rFileList.clear(); + + for (const auto &file : m_ArchiveMap) { + if (extension == BaseImporter::GetExtension(file.first)) + rFileList.push_back(file.first); + } + } + + bool ZipArchiveIOSystem::Implement::Exists(std::string& filename) { + MapArchive(); + + ZipFileInfoMap::const_iterator it = m_ArchiveMap.find(filename); + return (it != m_ArchiveMap.end()); + } + + IOStream * ZipArchiveIOSystem::Implement::OpenFile(std::string& filename) { + MapArchive(); + + SimplifyFilename(filename); + + // Find in the map + ZipFileInfoMap::const_iterator zip_it = m_ArchiveMap.find(filename); + if (zip_it == m_ArchiveMap.cend()) + return nullptr; + + const ZipFileInfo &zip_file = (*zip_it).second; + return zip_file.Extract(m_ZipFileHandle); + } + + inline void ReplaceAll(std::string& data, const std::string& before, const std::string& after) { + size_t pos = data.find(before); + while (pos != std::string::npos) + { + data.replace(pos, before.size(), after); + pos = data.find(before, pos + after.size()); + } + } + + inline void ReplaceAllChar(std::string& data, const char before, const char after) { + size_t pos = data.find(before); + while (pos != std::string::npos) + { + data[pos] = after; + pos = data.find(before, pos + 1); + } + } + + void ZipArchiveIOSystem::Implement::SimplifyFilename(std::string& filename) + { + ReplaceAllChar(filename, '\\', '/'); + + // Remove all . and / from the beginning of the path + size_t pos = filename.find_first_not_of("./"); + if (pos != 0) + filename.erase(0, pos); + + // Simplify "my/folder/../file.png" constructions, if any + static const std::string relative("/../"); + const size_t relsize = relative.size() - 1; + pos = filename.find(relative); + while (pos != std::string::npos) + { + // Previous slash + size_t prevpos = filename.rfind('/', pos - 1); + if (prevpos == pos) + filename.erase(0, pos + relative.size()); + else + filename.erase(prevpos, pos + relsize - prevpos); + + pos = filename.find(relative); + } + } + + ZipArchiveIOSystem::ZipArchiveIOSystem(IOSystem* pIOHandler, const char* pFilename, const char* pMode) + : pImpl(new Implement(pIOHandler, pFilename, pMode)) { + } + + // ---------------------------------------------------------------- + // The ZipArchiveIO + ZipArchiveIOSystem::ZipArchiveIOSystem(IOSystem* pIOHandler, const std::string& rFilename, const char* pMode) + : pImpl(new Implement(pIOHandler, rFilename.c_str(), pMode)) + { + } + + ZipArchiveIOSystem::~ZipArchiveIOSystem() { + delete pImpl; + } + + bool ZipArchiveIOSystem::Exists(const char* pFilename) const { + ai_assert(pFilename != nullptr); + + if (pFilename == nullptr) { + return false; + } + + std::string filename(pFilename); + return pImpl->Exists(filename); + } + + // This is always '/' in a ZIP + char ZipArchiveIOSystem::getOsSeparator() const { + return '/'; + } + + // Only supports Reading + IOStream * ZipArchiveIOSystem::Open(const char* pFilename, const char* pMode) { + ai_assert(pFilename != nullptr); + + for (size_t i = 0; pMode[i] != 0; ++i) + { + ai_assert(pMode[i] != 'w'); + if (pMode[i] == 'w') + return nullptr; + } + + std::string filename(pFilename); + return pImpl->OpenFile(filename); + } + + void ZipArchiveIOSystem::Close(IOStream* pFile) { + delete pFile; + } + + bool ZipArchiveIOSystem::isOpen() const { + return (pImpl->isOpen()); + } + + void ZipArchiveIOSystem::getFileList(std::vector& rFileList) const { + return pImpl->getFileList(rFileList); + } + + void ZipArchiveIOSystem::getFileListExtension(std::vector& rFileList, const std::string& extension) const { + return pImpl->getFileListExtension(rFileList, extension); + } + + bool ZipArchiveIOSystem::isZipArchive(IOSystem* pIOHandler, const char* pFilename) { + Implement tmp(pIOHandler, pFilename, "r"); + return tmp.isOpen(); + } + + bool ZipArchiveIOSystem::isZipArchive(IOSystem* pIOHandler, const std::string& rFilename) { + return isZipArchive(pIOHandler, rFilename.c_str()); + } + +} diff --git a/third_party/libassimp/code/assbin_chunks.h b/third_party/libassimp/code/Common/assbin_chunks.h similarity index 100% rename from third_party/libassimp/code/assbin_chunks.h rename to third_party/libassimp/code/Common/assbin_chunks.h diff --git a/third_party/libassimp/code/scene.cpp b/third_party/libassimp/code/Common/scene.cpp similarity index 99% rename from third_party/libassimp/code/scene.cpp rename to third_party/libassimp/code/Common/scene.cpp index 676051163d..2acb348d81 100644 --- a/third_party/libassimp/code/scene.cpp +++ b/third_party/libassimp/code/Common/scene.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/simd.cpp b/third_party/libassimp/code/Common/simd.cpp similarity index 98% rename from third_party/libassimp/code/simd.cpp rename to third_party/libassimp/code/Common/simd.cpp index 9e2a83a608..04615f408e 100644 --- a/third_party/libassimp/code/simd.cpp +++ b/third_party/libassimp/code/Common/simd.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/simd.h b/third_party/libassimp/code/Common/simd.h similarity index 98% rename from third_party/libassimp/code/simd.h rename to third_party/libassimp/code/Common/simd.h index 19117569d1..3eecdd4581 100644 --- a/third_party/libassimp/code/simd.h +++ b/third_party/libassimp/code/Common/simd.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/D3MFOpcPackage.cpp b/third_party/libassimp/code/D3MFOpcPackage.cpp deleted file mode 100644 index 8161a31e48..0000000000 --- a/third_party/libassimp/code/D3MFOpcPackage.cpp +++ /dev/null @@ -1,531 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2018, 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. - ----------------------------------------------------------------------- -*/ - -#ifndef ASSIMP_BUILD_NO_3MF_IMPORTER - -#include "D3MFOpcPackage.h" -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include "3MFXmlTags.h" - -namespace Assimp { - -namespace D3MF { - -class IOSystem2Unzip { -public: - static voidpf open(voidpf opaque, const char* filename, int mode); - static uLong read(voidpf opaque, voidpf stream, void* buf, uLong size); - static uLong write(voidpf opaque, voidpf stream, const void* buf, uLong size); - static long tell(voidpf opaque, voidpf stream); - static long seek(voidpf opaque, voidpf stream, uLong offset, int origin); - static int close(voidpf opaque, voidpf stream); - static int testerror(voidpf opaque, voidpf stream); - static zlib_filefunc_def get(IOSystem* pIOHandler); -}; - -voidpf IOSystem2Unzip::open(voidpf opaque, const char* filename, int mode) { - IOSystem* io_system = reinterpret_cast(opaque); - - const char* mode_fopen = NULL; - if((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) { - mode_fopen = "rb"; - } else { - if(mode & ZLIB_FILEFUNC_MODE_EXISTING) { - mode_fopen = "r+b"; - } else { - if(mode & ZLIB_FILEFUNC_MODE_CREATE) { - mode_fopen = "wb"; - } - } - } - - return (voidpf) io_system->Open(filename, mode_fopen); -} - -uLong IOSystem2Unzip::read(voidpf /*opaque*/, voidpf stream, void* buf, uLong size) { - IOStream* io_stream = (IOStream*) stream; - - return static_cast(io_stream->Read(buf, 1, size)); -} - -uLong IOSystem2Unzip::write(voidpf /*opaque*/, voidpf stream, const void* buf, uLong size) { - IOStream* io_stream = (IOStream*) stream; - - return static_cast(io_stream->Write(buf, 1, size)); -} - -long IOSystem2Unzip::tell(voidpf /*opaque*/, voidpf stream) { - IOStream* io_stream = (IOStream*) stream; - - return static_cast(io_stream->Tell()); -} - -long IOSystem2Unzip::seek(voidpf /*opaque*/, voidpf stream, uLong offset, int origin) { - IOStream* io_stream = (IOStream*) stream; - - aiOrigin assimp_origin; - switch (origin) { - default: - case ZLIB_FILEFUNC_SEEK_CUR: - assimp_origin = aiOrigin_CUR; - break; - case ZLIB_FILEFUNC_SEEK_END: - assimp_origin = aiOrigin_END; - break; - case ZLIB_FILEFUNC_SEEK_SET: - assimp_origin = aiOrigin_SET; - break; - } - - return (io_stream->Seek(offset, assimp_origin) == aiReturn_SUCCESS ? 0 : -1); -} - -int IOSystem2Unzip::close(voidpf opaque, voidpf stream) { - IOSystem* io_system = (IOSystem*) opaque; - IOStream* io_stream = (IOStream*) stream; - - io_system->Close(io_stream); - - return 0; -} - -int IOSystem2Unzip::testerror(voidpf /*opaque*/, voidpf /*stream*/) { - return 0; -} - -zlib_filefunc_def IOSystem2Unzip::get(IOSystem* pIOHandler) { - zlib_filefunc_def mapping; - - mapping.zopen_file = open; - mapping.zread_file = read; - mapping.zwrite_file = write; - mapping.ztell_file = tell; - mapping.zseek_file = seek; - mapping.zclose_file = close; - mapping.zerror_file = testerror; - mapping.opaque = reinterpret_cast(pIOHandler); - - return mapping; -} - -class ZipFile : public IOStream { - friend class D3MFZipArchive; - -public: - explicit ZipFile(size_t size); - virtual ~ZipFile(); - size_t Read(void* pvBuffer, size_t pSize, size_t pCount ); - size_t Write(const void* /*pvBuffer*/, size_t /*pSize*/, size_t /*pCount*/); - size_t FileSize() const; - aiReturn Seek(size_t /*pOffset*/, aiOrigin /*pOrigin*/); - size_t Tell() const; - void Flush(); - -private: - void *m_Buffer; - size_t m_Size; -}; - -ZipFile::ZipFile(size_t size) -: m_Buffer( nullptr ) -, m_Size(size) { - ai_assert(m_Size != 0); - m_Buffer = ::malloc(m_Size); -} - -ZipFile::~ZipFile() { - ::free(m_Buffer); - m_Buffer = NULL; -} - -size_t ZipFile::Read(void* pvBuffer, size_t pSize, size_t pCount) { - const size_t size = pSize * pCount; - ai_assert(size <= m_Size); - - std::memcpy(pvBuffer, m_Buffer, size); - - return size; -} - -size_t ZipFile::Write(const void* pvBuffer, size_t size, size_t pCount ) { - const size_t size_to_write( size * pCount ); - if ( 0 == size_to_write ) { - return 0U; - } - return 0U; -} - -size_t ZipFile::FileSize() const { - return m_Size; -} - -aiReturn ZipFile::Seek(size_t /*pOffset*/, aiOrigin /*pOrigin*/) { - return aiReturn_FAILURE; -} - -size_t ZipFile::Tell() const { - return 0; -} - -void ZipFile::Flush() { - // empty -} - -class D3MFZipArchive : public IOSystem { -public: - static const unsigned int FileNameSize = 256; - - D3MFZipArchive(IOSystem* pIOHandler, const std::string & rFile); - ~D3MFZipArchive(); - bool Exists(const char* pFile) const; - char getOsSeparator() const; - IOStream* Open(const char* pFile, const char* pMode = "rb"); - void Close(IOStream* pFile); - bool isOpen() const; - void getFileList(std::vector &rFileList); - -private: - bool mapArchive(); - -private: - unzFile m_ZipFileHandle; - std::map m_ArchiveMap; -}; - -// ------------------------------------------------------------------------------------------------ -// Constructor. -D3MFZipArchive::D3MFZipArchive(IOSystem* pIOHandler, const std::string& rFile) -: m_ZipFileHandle( nullptr ) -, m_ArchiveMap() { - if (! rFile.empty()) { - zlib_filefunc_def mapping = IOSystem2Unzip::get(pIOHandler); - - m_ZipFileHandle = unzOpen2(rFile.c_str(), &mapping); - if(m_ZipFileHandle != nullptr ) { - mapArchive(); - } - } -} - -// ------------------------------------------------------------------------------------------------ -// Destructor. -D3MFZipArchive::~D3MFZipArchive() { - for(auto &file : m_ArchiveMap) { - delete file.second; - } - m_ArchiveMap.clear(); - - if(m_ZipFileHandle != nullptr) { - unzClose(m_ZipFileHandle); - m_ZipFileHandle = nullptr; - } -} - -// ------------------------------------------------------------------------------------------------ -// Returns true, if the archive is already open. -bool D3MFZipArchive::isOpen() const { - return (m_ZipFileHandle != nullptr ); -} - -// ------------------------------------------------------------------------------------------------ -// Returns true, if the filename is part of the archive. -bool D3MFZipArchive::Exists(const char* pFile) const { - ai_assert(pFile != nullptr ); - - if ( pFile == nullptr ) { - return false; - } - - std::string filename(pFile); - std::map::const_iterator it = m_ArchiveMap.find(filename); - bool exist( false ); - if(it != m_ArchiveMap.end()) { - exist = true; - } - - return exist; -} - -// ------------------------------------------------------------------------------------------------ -// Returns the separator delimiter. -char D3MFZipArchive::getOsSeparator() const { -#ifndef _WIN32 - return '/'; -#else - return '\\'; -#endif -} - -// ------------------------------------------------------------------------------------------------ -// Opens a file, which is part of the archive. -IOStream *D3MFZipArchive::Open(const char* pFile, const char* /*pMode*/) { - ai_assert(pFile != NULL); - - IOStream* result = NULL; - - std::map::iterator it = m_ArchiveMap.find(pFile); - - if(it != m_ArchiveMap.end()) { - result = static_cast(it->second); - } - - return result; -} - -// ------------------------------------------------------------------------------------------------ -// Close a filestream. -void D3MFZipArchive::Close(IOStream *pFile) { - (void)(pFile); - ai_assert(pFile != NULL); - - // We don't do anything in case the file would be opened again in the future -} -// ------------------------------------------------------------------------------------------------ -// Returns the file-list of the archive. -void D3MFZipArchive::getFileList(std::vector &rFileList) { - rFileList.clear(); - - for(const auto &file : m_ArchiveMap) { - rFileList.push_back(file.first); - } -} - -// ------------------------------------------------------------------------------------------------ -// Maps the archive content. -bool D3MFZipArchive::mapArchive() { - bool success = false; - - if(m_ZipFileHandle != NULL) { - if(m_ArchiveMap.empty()) { - // At first ensure file is already open - if(unzGoToFirstFile(m_ZipFileHandle) == UNZ_OK) { - // Loop over all files - do { - char filename[FileNameSize]; - unz_file_info fileInfo; - - if(unzGetCurrentFileInfo(m_ZipFileHandle, &fileInfo, filename, FileNameSize, NULL, 0, NULL, 0) == UNZ_OK) { - // The file has EXACTLY the size of uncompressed_size. In C - // you need to mark the last character with '\0', so add - // another character - if(fileInfo.uncompressed_size != 0 && unzOpenCurrentFile(m_ZipFileHandle) == UNZ_OK) { - std::pair::iterator, bool> result = m_ArchiveMap.insert(std::make_pair(filename, new ZipFile(fileInfo.uncompressed_size))); - - if(unzReadCurrentFile(m_ZipFileHandle, result.first->second->m_Buffer, fileInfo.uncompressed_size) == (long int) fileInfo.uncompressed_size) { - if(unzCloseCurrentFile(m_ZipFileHandle) == UNZ_OK) { - // Nothing to do anymore... - } - } - } - } - } while(unzGoToNextFile(m_ZipFileHandle) != UNZ_END_OF_LIST_OF_FILE); - } - } - - success = true; - } - - return success; -} - -// ------------------------------------------------------------------------------------------------ - -typedef std::shared_ptr OpcPackageRelationshipPtr; - -class OpcPackageRelationshipReader { -public: - OpcPackageRelationshipReader(XmlReader* xmlReader) { - while(xmlReader->read()) { - if(xmlReader->getNodeType() == irr::io::EXN_ELEMENT && - xmlReader->getNodeName() == XmlTag::RELS_RELATIONSHIP_CONTAINER) - { - ParseRootNode(xmlReader); - } - } - } - - void ParseRootNode(XmlReader* xmlReader) - { - ParseAttributes(xmlReader); - - while(xmlReader->read()) - { - if(xmlReader->getNodeType() == irr::io::EXN_ELEMENT && - xmlReader->getNodeName() == XmlTag::RELS_RELATIONSHIP_NODE) - { - ParseChildNode(xmlReader); - } - } - } - - void ParseAttributes(XmlReader*) { - // empty - } - - bool validateRels( OpcPackageRelationshipPtr &relPtr ) { - if ( relPtr->id.empty() || relPtr->type.empty() || relPtr->target.empty() ) { - return false; - } - return true; - } - - void ParseChildNode(XmlReader* xmlReader) { - OpcPackageRelationshipPtr relPtr(new OpcPackageRelationship()); - - relPtr->id = xmlReader->getAttributeValueSafe(XmlTag::RELS_ATTRIB_ID.c_str()); - relPtr->type = xmlReader->getAttributeValueSafe(XmlTag::RELS_ATTRIB_TYPE.c_str()); - relPtr->target = xmlReader->getAttributeValueSafe(XmlTag::RELS_ATTRIB_TARGET.c_str()); - if ( validateRels( relPtr ) ) { - m_relationShips.push_back( relPtr ); - } - } - - std::vector m_relationShips; -}; - -// ------------------------------------------------------------------------------------------------ -D3MFOpcPackage::D3MFOpcPackage(IOSystem* pIOHandler, const std::string& rFile) -: mRootStream(nullptr) -, mZipArchive() { - mZipArchive.reset( new D3MF::D3MFZipArchive( pIOHandler, rFile ) ); - if(!mZipArchive->isOpen()) { - throw DeadlyImportError("Failed to open file " + rFile+ "."); - } - - std::vector fileList; - mZipArchive->getFileList(fileList); - - for (auto& file: fileList) { - if(file == D3MF::XmlTag::ROOT_RELATIONSHIPS_ARCHIVE) { - //PkgRelationshipReader pkgRelReader(file, archive); - ai_assert(mZipArchive->Exists(file.c_str())); - - IOStream *fileStream = mZipArchive->Open(file.c_str()); - - ai_assert(fileStream != nullptr); - - std::string rootFile = ReadPackageRootRelationship(fileStream); - if ( rootFile.size() > 0 && rootFile[ 0 ] == '/' ) { - rootFile = rootFile.substr( 1 ); - if ( rootFile[ 0 ] == '/' ) { - // deal with zip-bug - rootFile = rootFile.substr( 1 ); - } - } - - ASSIMP_LOG_DEBUG(rootFile); - - mRootStream = mZipArchive->Open(rootFile.c_str()); - ai_assert( mRootStream != nullptr ); - if ( nullptr == mRootStream ) { - throw DeadlyExportError( "Cannot open root-file in archive : " + rootFile ); - } - - mZipArchive->Close( fileStream ); - - } else if( file == D3MF::XmlTag::CONTENT_TYPES_ARCHIVE) { - - } - } -} - -D3MFOpcPackage::~D3MFOpcPackage() { - // empty -} - -IOStream* D3MFOpcPackage::RootStream() const { - return mRootStream; -} - -static const std::string ModelRef = "3D/3dmodel.model"; - -bool D3MFOpcPackage::validate() { - if ( nullptr == mRootStream || nullptr == mZipArchive ) { - return false; - } - - return mZipArchive->Exists( ModelRef.c_str() ); -} - -bool D3MFOpcPackage::isZipArchive( IOSystem* pIOHandler, const std::string& rFile ) { - D3MF::D3MFZipArchive ar( pIOHandler, rFile ); - if ( !ar.isOpen() ) { - return false; - } - - return true; -} - -std::string D3MFOpcPackage::ReadPackageRootRelationship(IOStream* stream) { - std::unique_ptr xmlStream(new CIrrXML_IOStreamReader(stream)); - std::unique_ptr xml(irr::io::createIrrXMLReader(xmlStream.get())); - - OpcPackageRelationshipReader reader(xml.get()); - - auto itr = std::find_if(reader.m_relationShips.begin(), reader.m_relationShips.end(), [](const OpcPackageRelationshipPtr& rel){ - return rel->type == XmlTag::PACKAGE_START_PART_RELATIONSHIP_TYPE; - }); - - if ( itr == reader.m_relationShips.end() ) { - throw DeadlyImportError( "Cannot find " + XmlTag::PACKAGE_START_PART_RELATIONSHIP_TYPE ); - } - - return (*itr)->target; -} - -} // Namespace D3MF -} // Namespace Assimp - -#endif //ASSIMP_BUILD_NO_3MF_IMPORTER diff --git a/third_party/libassimp/code/DXFHelper.h b/third_party/libassimp/code/DXF/DXFHelper.h similarity index 99% rename from third_party/libassimp/code/DXFHelper.h rename to third_party/libassimp/code/DXF/DXFHelper.h index daf2f97e20..0ec8e130be 100644 --- a/third_party/libassimp/code/DXFHelper.h +++ b/third_party/libassimp/code/DXF/DXFHelper.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/DXFLoader.cpp b/third_party/libassimp/code/DXF/DXFLoader.cpp similarity index 99% rename from third_party/libassimp/code/DXFLoader.cpp rename to third_party/libassimp/code/DXF/DXFLoader.cpp index 6710597df0..baf3154859 100644 --- a/third_party/libassimp/code/DXFLoader.cpp +++ b/third_party/libassimp/code/DXF/DXFLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -48,12 +48,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_DXF_IMPORTER -#include "DXFLoader.h" -#include -#include "ConvertToLHProcess.h" -#include +#include "DXF/DXFLoader.h" +#include "DXF/DXFHelper.h" +#include "PostProcessing/ConvertToLHProcess.h" -#include "DXFHelper.h" +#include +#include #include #include #include diff --git a/third_party/libassimp/code/DXFLoader.h b/third_party/libassimp/code/DXF/DXFLoader.h similarity index 99% rename from third_party/libassimp/code/DXFLoader.h rename to third_party/libassimp/code/DXF/DXFLoader.h index e7f534e985..044cf6bcb7 100644 --- a/third_party/libassimp/code/DXFLoader.h +++ b/third_party/libassimp/code/DXF/DXFLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/FBXAnimation.cpp b/third_party/libassimp/code/FBX/FBXAnimation.cpp similarity index 98% rename from third_party/libassimp/code/FBXAnimation.cpp rename to third_party/libassimp/code/FBX/FBXAnimation.cpp index 24ab9b14b4..874914431b 100644 --- a/third_party/libassimp/code/FBXAnimation.cpp +++ b/third_party/libassimp/code/FBX/FBXAnimation.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -105,8 +105,8 @@ AnimationCurveNode::AnimationCurveNode(uint64_t id, const Element& element, cons const Scope& sc = GetRequiredScope(element); // find target node - const char* whitelist[] = {"Model","NodeAttribute"}; - const std::vector& conns = doc.GetConnectionsBySourceSequenced(ID(),whitelist,2); + const char* whitelist[] = {"Model","NodeAttribute","Deformer"}; + const std::vector& conns = doc.GetConnectionsBySourceSequenced(ID(),whitelist,3); for(const Connection* con : conns) { diff --git a/third_party/libassimp/code/FBXBinaryTokenizer.cpp b/third_party/libassimp/code/FBX/FBXBinaryTokenizer.cpp similarity index 96% rename from third_party/libassimp/code/FBXBinaryTokenizer.cpp rename to third_party/libassimp/code/FBX/FBXBinaryTokenizer.cpp index b81a9f9455..a4a2bc8e79 100644 --- a/third_party/libassimp/code/FBXBinaryTokenizer.cpp +++ b/third_party/libassimp/code/FBX/FBXBinaryTokenizer.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -83,7 +83,7 @@ namespace FBX { // e_unknown_21 = 1 << 21, // e_unknown_22 = 1 << 22, // e_unknown_23 = 1 << 23, -// e_flag_field_size_64_bit = 1 << 24, // Not sure what is +// e_flag_field_size_64_bit = 1 << 24, // Not sure what is // e_unknown_25 = 1 << 25, // e_unknown_26 = 1 << 26, // e_unknown_27 = 1 << 27, @@ -98,7 +98,7 @@ namespace FBX { // return (flags & to_check) != 0; //} // ------------------------------------------------------------------------------------------------ -Token::Token(const char* sbegin, const char* send, TokenType type, unsigned int offset) +Token::Token(const char* sbegin, const char* send, TokenType type, size_t offset) : #ifdef DEBUG contents(sbegin, static_cast(send-sbegin)), @@ -122,18 +122,18 @@ namespace { // ------------------------------------------------------------------------------------------------ // signal tokenization error, this is always unrecoverable. Throws DeadlyImportError. -AI_WONT_RETURN void TokenizeError(const std::string& message, unsigned int offset) AI_WONT_RETURN_SUFFIX; -AI_WONT_RETURN void TokenizeError(const std::string& message, unsigned int offset) +AI_WONT_RETURN void TokenizeError(const std::string& message, size_t offset) AI_WONT_RETURN_SUFFIX; +AI_WONT_RETURN void TokenizeError(const std::string& message, size_t offset) { throw DeadlyImportError(Util::AddOffset("FBX-Tokenize",message,offset)); } // ------------------------------------------------------------------------------------------------ -uint32_t Offset(const char* begin, const char* cursor) { +size_t Offset(const char* begin, const char* cursor) { ai_assert(begin <= cursor); - return static_cast(cursor - begin); + return cursor - begin; } // ------------------------------------------------------------------------------------------------ @@ -276,8 +276,8 @@ void ReadData(const char*& sbegin_out, const char*& send_out, const char* input, case 'f': case 'd': case 'l': - case 'i': { - + case 'i': + case 'c': { const uint32_t length = ReadWord(input, cursor, end); const uint32_t encoding = ReadWord(input, cursor, end); @@ -298,6 +298,10 @@ void ReadData(const char*& sbegin_out, const char*& send_out, const char* input, stride = 8; break; + case 'c': + stride = 1; + break; + default: ai_assert(false); }; @@ -420,7 +424,7 @@ bool ReadScope(TokenList& output_tokens, const char* input, const char*& cursor, // ------------------------------------------------------------------------------------------------ // TODO: Test FBX Binary files newer than the 7500 version to check if the 64 bits address behaviour is consistent -void TokenizeBinary(TokenList& output_tokens, const char* input, unsigned int length) +void TokenizeBinary(TokenList& output_tokens, const char* input, size_t length) { ai_assert(input); diff --git a/third_party/libassimp/code/FBXCommon.h b/third_party/libassimp/code/FBX/FBXCommon.h similarity index 98% rename from third_party/libassimp/code/FBXCommon.h rename to third_party/libassimp/code/FBX/FBXCommon.h index 60b040552f..e516449130 100644 --- a/third_party/libassimp/code/FBXCommon.h +++ b/third_party/libassimp/code/FBX/FBXCommon.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -47,7 +47,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_FBX_EXPORTER - +namespace Assimp { namespace FBX { const std::string NULL_RECORD = { // 13 null bytes @@ -80,7 +80,7 @@ namespace FBX TransformInheritance_MAX // end-of-enum sentinel }; } - +} #endif // ASSIMP_BUILD_NO_FBX_EXPORTER #endif // AI_FBXCOMMON_H_INC diff --git a/third_party/libassimp/code/FBXCompileConfig.h b/third_party/libassimp/code/FBX/FBXCompileConfig.h similarity index 98% rename from third_party/libassimp/code/FBXCompileConfig.h rename to third_party/libassimp/code/FBX/FBXCompileConfig.h index 2e7336e85d..3a3841fa5b 100644 --- a/third_party/libassimp/code/FBXCompileConfig.h +++ b/third_party/libassimp/code/FBX/FBXCompileConfig.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/FBX/FBXConverter.cpp b/third_party/libassimp/code/FBX/FBXConverter.cpp new file mode 100644 index 0000000000..152be32772 --- /dev/null +++ b/third_party/libassimp/code/FBX/FBXConverter.cpp @@ -0,0 +1,3615 @@ +/* +Open Asset Import Library (assimp) +---------------------------------------------------------------------- + +Copyright (c) 2006-2019, 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 FBXConverter.cpp + * @brief Implementation of the FBX DOM -> aiScene converter + */ + +#ifndef ASSIMP_BUILD_NO_FBX_IMPORTER + +#include "FBXConverter.h" +#include "FBXParser.h" +#include "FBXMeshGeometry.h" +#include "FBXDocument.h" +#include "FBXUtil.h" +#include "FBXProperties.h" +#include "FBXImporter.h" + +#include +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + + +namespace Assimp { + namespace FBX { + + using namespace Util; + +#define MAGIC_NODE_TAG "_$AssimpFbx$" + +#define CONVERT_FBX_TIME(time) static_cast(time) / 46186158000L + + FBXConverter::FBXConverter(aiScene* out, const Document& doc, bool removeEmptyBones ) + : defaultMaterialIndex() + , lights() + , cameras() + , textures() + , materials_converted() + , textures_converted() + , meshes_converted() + , node_anim_chain_bits() + , mNodeNames() + , anim_fps() + , out(out) + , doc(doc) { + // animations need to be converted first since this will + // populate the node_anim_chain_bits map, which is needed + // to determine which nodes need to be generated. + ConvertAnimations(); + ConvertRootNode(); + + if (doc.Settings().readAllMaterials) { + // unfortunately this means we have to evaluate all objects + for (const ObjectMap::value_type& v : doc.Objects()) { + + const Object* ob = v.second->Get(); + if (!ob) { + continue; + } + + const Material* mat = dynamic_cast(ob); + if (mat) { + + if (materials_converted.find(mat) == materials_converted.end()) { + ConvertMaterial(*mat, 0); + } + } + } + } + + ConvertGlobalSettings(); + TransferDataToScene(); + + // if we didn't read any meshes set the AI_SCENE_FLAGS_INCOMPLETE + // to make sure the scene passes assimp's validation. FBX files + // need not contain geometry (i.e. camera animations, raw armatures). + if (out->mNumMeshes == 0) { + out->mFlags |= AI_SCENE_FLAGS_INCOMPLETE; + } + } + + + FBXConverter::~FBXConverter() { + std::for_each(meshes.begin(), meshes.end(), Util::delete_fun()); + std::for_each(materials.begin(), materials.end(), Util::delete_fun()); + std::for_each(animations.begin(), animations.end(), Util::delete_fun()); + std::for_each(lights.begin(), lights.end(), Util::delete_fun()); + std::for_each(cameras.begin(), cameras.end(), Util::delete_fun()); + std::for_each(textures.begin(), textures.end(), Util::delete_fun()); + } + + void FBXConverter::ConvertRootNode() { + out->mRootNode = new aiNode(); + std::string unique_name; + GetUniqueName("RootNode", unique_name); + out->mRootNode->mName.Set(unique_name); + + // root has ID 0 + ConvertNodes(0L, *out->mRootNode); + } + + static std::string getAncestorBaseName(const aiNode* node) + { + const char* nodeName = nullptr; + size_t length = 0; + while (node && (!nodeName || length == 0)) + { + nodeName = node->mName.C_Str(); + length = node->mName.length; + node = node->mParent; + } + + if (!nodeName || length == 0) + { + return {}; + } + // could be std::string_view if c++17 available + return std::string(nodeName, length); + } + + // Make unique name + std::string FBXConverter::MakeUniqueNodeName(const Model* const model, const aiNode& parent) + { + std::string original_name = FixNodeName(model->Name()); + if (original_name.empty()) + { + original_name = getAncestorBaseName(&parent); + } + std::string unique_name; + GetUniqueName(original_name, unique_name); + return unique_name; + } + + void FBXConverter::ConvertNodes(uint64_t id, aiNode& parent, const aiMatrix4x4& parent_transform) { + const std::vector& conns = doc.GetConnectionsByDestinationSequenced(id, "Model"); + + std::vector nodes; + nodes.reserve(conns.size()); + + std::vector nodes_chain; + std::vector post_nodes_chain; + + try { + for (const Connection* con : conns) { + + // ignore object-property links + if (con->PropertyName().length()) { + continue; + } + + const Object* const object = con->SourceObject(); + if (nullptr == object) { + FBXImporter::LogWarn("failed to convert source object for Model link"); + continue; + } + + const Model* const model = dynamic_cast(object); + + if (nullptr != model) { + nodes_chain.clear(); + post_nodes_chain.clear(); + + aiMatrix4x4 new_abs_transform = parent_transform; + + std::string unique_name = MakeUniqueNodeName(model, parent); + + // even though there is only a single input node, the design of + // assimp (or rather: the complicated transformation chain that + // is employed by fbx) means that we may need multiple aiNode's + // to represent a fbx node's transformation. + const bool need_additional_node = GenerateTransformationNodeChain(*model, unique_name, nodes_chain, post_nodes_chain); + + ai_assert(nodes_chain.size()); + + if (need_additional_node) { + nodes_chain.push_back(new aiNode(unique_name)); + } + + //setup metadata on newest node + SetupNodeMetadata(*model, *nodes_chain.back()); + + // link all nodes in a row + aiNode* last_parent = &parent; + for (aiNode* prenode : nodes_chain) { + ai_assert(prenode); + + if (last_parent != &parent) { + last_parent->mNumChildren = 1; + last_parent->mChildren = new aiNode*[1]; + last_parent->mChildren[0] = prenode; + } + + prenode->mParent = last_parent; + last_parent = prenode; + + new_abs_transform *= prenode->mTransformation; + } + + // attach geometry + ConvertModel(*model, *nodes_chain.back(), new_abs_transform); + + // check if there will be any child nodes + const std::vector& child_conns + = doc.GetConnectionsByDestinationSequenced(model->ID(), "Model"); + + // if so, link the geometric transform inverse nodes + // before we attach any child nodes + if (child_conns.size()) { + for (aiNode* postnode : post_nodes_chain) { + ai_assert(postnode); + + if (last_parent != &parent) { + last_parent->mNumChildren = 1; + last_parent->mChildren = new aiNode*[1]; + last_parent->mChildren[0] = postnode; + } + + postnode->mParent = last_parent; + last_parent = postnode; + + new_abs_transform *= postnode->mTransformation; + } + } + else { + // free the nodes we allocated as we don't need them + Util::delete_fun deleter; + std::for_each( + post_nodes_chain.begin(), + post_nodes_chain.end(), + deleter + ); + } + + // attach sub-nodes (if any) + ConvertNodes(model->ID(), *last_parent, new_abs_transform); + + if (doc.Settings().readLights) { + ConvertLights(*model, unique_name); + } + + if (doc.Settings().readCameras) { + ConvertCameras(*model, unique_name); + } + + nodes.push_back(nodes_chain.front()); + nodes_chain.clear(); + } + } + + if (nodes.size()) { + parent.mChildren = new aiNode*[nodes.size()](); + parent.mNumChildren = static_cast(nodes.size()); + + std::swap_ranges(nodes.begin(), nodes.end(), parent.mChildren); + } + } + catch (std::exception&) { + Util::delete_fun deleter; + std::for_each(nodes.begin(), nodes.end(), deleter); + std::for_each(nodes_chain.begin(), nodes_chain.end(), deleter); + std::for_each(post_nodes_chain.begin(), post_nodes_chain.end(), deleter); + } + } + + + void FBXConverter::ConvertLights(const Model& model, const std::string &orig_name) { + const std::vector& node_attrs = model.GetAttributes(); + for (const NodeAttribute* attr : node_attrs) { + const Light* const light = dynamic_cast(attr); + if (light) { + ConvertLight(*light, orig_name); + } + } + } + + void FBXConverter::ConvertCameras(const Model& model, const std::string &orig_name) { + const std::vector& node_attrs = model.GetAttributes(); + for (const NodeAttribute* attr : node_attrs) { + const Camera* const cam = dynamic_cast(attr); + if (cam) { + ConvertCamera(*cam, orig_name); + } + } + } + + void FBXConverter::ConvertLight(const Light& light, const std::string &orig_name) { + lights.push_back(new aiLight()); + aiLight* const out_light = lights.back(); + + out_light->mName.Set(orig_name); + + const float intensity = light.Intensity() / 100.0f; + const aiVector3D& col = light.Color(); + + out_light->mColorDiffuse = aiColor3D(col.x, col.y, col.z); + out_light->mColorDiffuse.r *= intensity; + out_light->mColorDiffuse.g *= intensity; + out_light->mColorDiffuse.b *= intensity; + + out_light->mColorSpecular = out_light->mColorDiffuse; + + //lights are defined along negative y direction + out_light->mPosition = aiVector3D(0.0f); + out_light->mDirection = aiVector3D(0.0f, -1.0f, 0.0f); + out_light->mUp = aiVector3D(0.0f, 0.0f, -1.0f); + + switch (light.LightType()) + { + case Light::Type_Point: + out_light->mType = aiLightSource_POINT; + break; + + case Light::Type_Directional: + out_light->mType = aiLightSource_DIRECTIONAL; + break; + + case Light::Type_Spot: + out_light->mType = aiLightSource_SPOT; + out_light->mAngleOuterCone = AI_DEG_TO_RAD(light.OuterAngle()); + out_light->mAngleInnerCone = AI_DEG_TO_RAD(light.InnerAngle()); + break; + + case Light::Type_Area: + FBXImporter::LogWarn("cannot represent area light, set to UNDEFINED"); + out_light->mType = aiLightSource_UNDEFINED; + break; + + case Light::Type_Volume: + FBXImporter::LogWarn("cannot represent volume light, set to UNDEFINED"); + out_light->mType = aiLightSource_UNDEFINED; + break; + default: + ai_assert(false); + } + + float decay = light.DecayStart(); + switch (light.DecayType()) + { + case Light::Decay_None: + out_light->mAttenuationConstant = decay; + out_light->mAttenuationLinear = 0.0f; + out_light->mAttenuationQuadratic = 0.0f; + break; + case Light::Decay_Linear: + out_light->mAttenuationConstant = 0.0f; + out_light->mAttenuationLinear = 2.0f / decay; + out_light->mAttenuationQuadratic = 0.0f; + break; + case Light::Decay_Quadratic: + out_light->mAttenuationConstant = 0.0f; + out_light->mAttenuationLinear = 0.0f; + out_light->mAttenuationQuadratic = 2.0f / (decay * decay); + break; + case Light::Decay_Cubic: + FBXImporter::LogWarn("cannot represent cubic attenuation, set to Quadratic"); + out_light->mAttenuationQuadratic = 1.0f; + break; + default: + ai_assert(false); + break; + } + } + + void FBXConverter::ConvertCamera(const Camera& cam, const std::string &orig_name) + { + cameras.push_back(new aiCamera()); + aiCamera* const out_camera = cameras.back(); + + out_camera->mName.Set(orig_name); + + out_camera->mAspect = cam.AspectWidth() / cam.AspectHeight(); + + out_camera->mPosition = aiVector3D(0.0f); + out_camera->mLookAt = aiVector3D(1.0f, 0.0f, 0.0f); + out_camera->mUp = aiVector3D(0.0f, 1.0f, 0.0f); + + out_camera->mHorizontalFOV = AI_DEG_TO_RAD(cam.FieldOfView()); + + out_camera->mClipPlaneNear = cam.NearPlane(); + out_camera->mClipPlaneFar = cam.FarPlane(); + + out_camera->mHorizontalFOV = AI_DEG_TO_RAD(cam.FieldOfView()); + out_camera->mClipPlaneNear = cam.NearPlane(); + out_camera->mClipPlaneFar = cam.FarPlane(); + } + + void FBXConverter::GetUniqueName(const std::string &name, std::string &uniqueName) + { + uniqueName = name; + auto it_pair = mNodeNames.insert({ name, 0 }); // duplicate node name instance count + unsigned int& i = it_pair.first->second; + while (!it_pair.second) + { + i++; + std::ostringstream ext; + ext << name << std::setfill('0') << std::setw(3) << i; + uniqueName = ext.str(); + it_pair = mNodeNames.insert({ uniqueName, 0 }); + } + } + + const char* FBXConverter::NameTransformationComp(TransformationComp comp) { + switch (comp) { + case TransformationComp_Translation: + return "Translation"; + case TransformationComp_RotationOffset: + return "RotationOffset"; + case TransformationComp_RotationPivot: + return "RotationPivot"; + case TransformationComp_PreRotation: + return "PreRotation"; + case TransformationComp_Rotation: + return "Rotation"; + case TransformationComp_PostRotation: + return "PostRotation"; + case TransformationComp_RotationPivotInverse: + return "RotationPivotInverse"; + case TransformationComp_ScalingOffset: + return "ScalingOffset"; + case TransformationComp_ScalingPivot: + return "ScalingPivot"; + case TransformationComp_Scaling: + return "Scaling"; + case TransformationComp_ScalingPivotInverse: + return "ScalingPivotInverse"; + case TransformationComp_GeometricScaling: + return "GeometricScaling"; + case TransformationComp_GeometricRotation: + return "GeometricRotation"; + case TransformationComp_GeometricTranslation: + return "GeometricTranslation"; + case TransformationComp_GeometricScalingInverse: + return "GeometricScalingInverse"; + case TransformationComp_GeometricRotationInverse: + return "GeometricRotationInverse"; + case TransformationComp_GeometricTranslationInverse: + return "GeometricTranslationInverse"; + case TransformationComp_MAXIMUM: // this is to silence compiler warnings + default: + break; + } + + ai_assert(false); + + return nullptr; + } + + const char* FBXConverter::NameTransformationCompProperty(TransformationComp comp) { + switch (comp) { + case TransformationComp_Translation: + return "Lcl Translation"; + case TransformationComp_RotationOffset: + return "RotationOffset"; + case TransformationComp_RotationPivot: + return "RotationPivot"; + case TransformationComp_PreRotation: + return "PreRotation"; + case TransformationComp_Rotation: + return "Lcl Rotation"; + case TransformationComp_PostRotation: + return "PostRotation"; + case TransformationComp_RotationPivotInverse: + return "RotationPivotInverse"; + case TransformationComp_ScalingOffset: + return "ScalingOffset"; + case TransformationComp_ScalingPivot: + return "ScalingPivot"; + case TransformationComp_Scaling: + return "Lcl Scaling"; + case TransformationComp_ScalingPivotInverse: + return "ScalingPivotInverse"; + case TransformationComp_GeometricScaling: + return "GeometricScaling"; + case TransformationComp_GeometricRotation: + return "GeometricRotation"; + case TransformationComp_GeometricTranslation: + return "GeometricTranslation"; + case TransformationComp_GeometricScalingInverse: + return "GeometricScalingInverse"; + case TransformationComp_GeometricRotationInverse: + return "GeometricRotationInverse"; + case TransformationComp_GeometricTranslationInverse: + return "GeometricTranslationInverse"; + case TransformationComp_MAXIMUM: // this is to silence compiler warnings + break; + } + + ai_assert(false); + + return nullptr; + } + + aiVector3D FBXConverter::TransformationCompDefaultValue(TransformationComp comp) + { + // XXX a neat way to solve the never-ending special cases for scaling + // would be to do everything in log space! + return comp == TransformationComp_Scaling ? aiVector3D(1.f, 1.f, 1.f) : aiVector3D(); + } + + void FBXConverter::GetRotationMatrix(Model::RotOrder mode, const aiVector3D& rotation, aiMatrix4x4& out) + { + if (mode == Model::RotOrder_SphericXYZ) { + FBXImporter::LogError("Unsupported RotationMode: SphericXYZ"); + out = aiMatrix4x4(); + return; + } + + const float angle_epsilon = Math::getEpsilon(); + + out = aiMatrix4x4(); + + bool is_id[3] = { true, true, true }; + + aiMatrix4x4 temp[3]; + if (std::fabs(rotation.z) > angle_epsilon) { + aiMatrix4x4::RotationZ(AI_DEG_TO_RAD(rotation.z), temp[2]); + is_id[2] = false; + } + if (std::fabs(rotation.y) > angle_epsilon) { + aiMatrix4x4::RotationY(AI_DEG_TO_RAD(rotation.y), temp[1]); + is_id[1] = false; + } + if (std::fabs(rotation.x) > angle_epsilon) { + aiMatrix4x4::RotationX(AI_DEG_TO_RAD(rotation.x), temp[0]); + is_id[0] = false; + } + + int order[3] = { -1, -1, -1 }; + + // note: rotation order is inverted since we're left multiplying as is usual in assimp + switch (mode) + { + case Model::RotOrder_EulerXYZ: + order[0] = 2; + order[1] = 1; + order[2] = 0; + break; + + case Model::RotOrder_EulerXZY: + order[0] = 1; + order[1] = 2; + order[2] = 0; + break; + + case Model::RotOrder_EulerYZX: + order[0] = 0; + order[1] = 2; + order[2] = 1; + break; + + case Model::RotOrder_EulerYXZ: + order[0] = 2; + order[1] = 0; + order[2] = 1; + break; + + case Model::RotOrder_EulerZXY: + order[0] = 1; + order[1] = 0; + order[2] = 2; + break; + + case Model::RotOrder_EulerZYX: + order[0] = 0; + order[1] = 1; + order[2] = 2; + break; + + default: + ai_assert(false); + break; + } + + ai_assert(order[0] >= 0); + ai_assert(order[0] <= 2); + ai_assert(order[1] >= 0); + ai_assert(order[1] <= 2); + ai_assert(order[2] >= 0); + ai_assert(order[2] <= 2); + + if (!is_id[order[0]]) { + out = temp[order[0]]; + } + + if (!is_id[order[1]]) { + out = out * temp[order[1]]; + } + + if (!is_id[order[2]]) { + out = out * temp[order[2]]; + } + } + + bool FBXConverter::NeedsComplexTransformationChain(const Model& model) + { + const PropertyTable& props = model.Props(); + bool ok; + + const float zero_epsilon = 1e-6f; + const aiVector3D all_ones(1.0f, 1.0f, 1.0f); + for (size_t i = 0; i < TransformationComp_MAXIMUM; ++i) { + const TransformationComp comp = static_cast(i); + + if (comp == TransformationComp_Rotation || comp == TransformationComp_Scaling || comp == TransformationComp_Translation) { + continue; + } + + bool scale_compare = (comp == TransformationComp_GeometricScaling || comp == TransformationComp_Scaling); + + const aiVector3D& v = PropertyGet(props, NameTransformationCompProperty(comp), ok); + if (ok && scale_compare) { + if ((v - all_ones).SquareLength() > zero_epsilon) { + return true; + } + } else if (ok) { + if (v.SquareLength() > zero_epsilon) { + return true; + } + } + } + + return false; + } + + std::string FBXConverter::NameTransformationChainNode(const std::string& name, TransformationComp comp) + { + return name + std::string(MAGIC_NODE_TAG) + "_" + NameTransformationComp(comp); + } + + bool FBXConverter::GenerateTransformationNodeChain(const Model& model, const std::string& name, std::vector& output_nodes, + std::vector& post_output_nodes) { + const PropertyTable& props = model.Props(); + const Model::RotOrder rot = model.RotationOrder(); + + bool ok; + + aiMatrix4x4 chain[TransformationComp_MAXIMUM]; + + ai_assert(TransformationComp_MAXIMUM < 32); + std::uint32_t chainBits = 0; + // A node won't need a node chain if it only has these. + const std::uint32_t chainMaskSimple = (1 << TransformationComp_Translation) + (1 << TransformationComp_Scaling) + (1 << TransformationComp_Rotation); + // A node will need a node chain if it has any of these. + const std::uint32_t chainMaskComplex = ((1 << (TransformationComp_MAXIMUM)) - 1) - chainMaskSimple; + + std::fill_n(chain, static_cast(TransformationComp_MAXIMUM), aiMatrix4x4()); + + // generate transformation matrices for all the different transformation components + const float zero_epsilon = Math::getEpsilon(); + const aiVector3D all_ones(1.0f, 1.0f, 1.0f); + + const aiVector3D& PreRotation = PropertyGet(props, "PreRotation", ok); + if (ok && PreRotation.SquareLength() > zero_epsilon) { + chainBits = chainBits | (1 << TransformationComp_PreRotation); + + GetRotationMatrix(Model::RotOrder::RotOrder_EulerXYZ, PreRotation, chain[TransformationComp_PreRotation]); + } + + const aiVector3D& PostRotation = PropertyGet(props, "PostRotation", ok); + if (ok && PostRotation.SquareLength() > zero_epsilon) { + chainBits = chainBits | (1 << TransformationComp_PostRotation); + + GetRotationMatrix(Model::RotOrder::RotOrder_EulerXYZ, PostRotation, chain[TransformationComp_PostRotation]); + } + + const aiVector3D& RotationPivot = PropertyGet(props, "RotationPivot", ok); + if (ok && RotationPivot.SquareLength() > zero_epsilon) { + chainBits = chainBits | (1 << TransformationComp_RotationPivot) | (1 << TransformationComp_RotationPivotInverse); + + aiMatrix4x4::Translation(RotationPivot, chain[TransformationComp_RotationPivot]); + aiMatrix4x4::Translation(-RotationPivot, chain[TransformationComp_RotationPivotInverse]); + } + + const aiVector3D& RotationOffset = PropertyGet(props, "RotationOffset", ok); + if (ok && RotationOffset.SquareLength() > zero_epsilon) { + chainBits = chainBits | (1 << TransformationComp_RotationOffset); + + aiMatrix4x4::Translation(RotationOffset, chain[TransformationComp_RotationOffset]); + } + + const aiVector3D& ScalingOffset = PropertyGet(props, "ScalingOffset", ok); + if (ok && ScalingOffset.SquareLength() > zero_epsilon) { + chainBits = chainBits | (1 << TransformationComp_ScalingOffset); + + aiMatrix4x4::Translation(ScalingOffset, chain[TransformationComp_ScalingOffset]); + } + + const aiVector3D& ScalingPivot = PropertyGet(props, "ScalingPivot", ok); + if (ok && ScalingPivot.SquareLength() > zero_epsilon) { + chainBits = chainBits | (1 << TransformationComp_ScalingPivot) | (1 << TransformationComp_ScalingPivotInverse); + + aiMatrix4x4::Translation(ScalingPivot, chain[TransformationComp_ScalingPivot]); + aiMatrix4x4::Translation(-ScalingPivot, chain[TransformationComp_ScalingPivotInverse]); + } + + const aiVector3D& Translation = PropertyGet(props, "Lcl Translation", ok); + if (ok && Translation.SquareLength() > zero_epsilon) { + chainBits = chainBits | (1 << TransformationComp_Translation); + + aiMatrix4x4::Translation(Translation, chain[TransformationComp_Translation]); + } + + const aiVector3D& Scaling = PropertyGet(props, "Lcl Scaling", ok); + if (ok && (Scaling - all_ones).SquareLength() > zero_epsilon) { + chainBits = chainBits | (1 << TransformationComp_Scaling); + + aiMatrix4x4::Scaling(Scaling, chain[TransformationComp_Scaling]); + } + + const aiVector3D& Rotation = PropertyGet(props, "Lcl Rotation", ok); + if (ok && Rotation.SquareLength() > zero_epsilon) { + chainBits = chainBits | (1 << TransformationComp_Rotation); + + GetRotationMatrix(rot, Rotation, chain[TransformationComp_Rotation]); + } + + const aiVector3D& GeometricScaling = PropertyGet(props, "GeometricScaling", ok); + if (ok && (GeometricScaling - all_ones).SquareLength() > zero_epsilon) { + chainBits = chainBits | (1 << TransformationComp_GeometricScaling); + aiMatrix4x4::Scaling(GeometricScaling, chain[TransformationComp_GeometricScaling]); + aiVector3D GeometricScalingInverse = GeometricScaling; + bool canscale = true; + for (unsigned int i = 0; i < 3; ++i) { + if (std::fabs(GeometricScalingInverse[i]) > zero_epsilon) { + GeometricScalingInverse[i] = 1.0f / GeometricScaling[i]; + } + else { + FBXImporter::LogError("cannot invert geometric scaling matrix with a 0.0 scale component"); + canscale = false; + break; + } + } + if (canscale) { + chainBits = chainBits | (1 << TransformationComp_GeometricScalingInverse); + aiMatrix4x4::Scaling(GeometricScalingInverse, chain[TransformationComp_GeometricScalingInverse]); + } + } + + const aiVector3D& GeometricRotation = PropertyGet(props, "GeometricRotation", ok); + if (ok && GeometricRotation.SquareLength() > zero_epsilon) { + chainBits = chainBits | (1 << TransformationComp_GeometricRotation) | (1 << TransformationComp_GeometricRotationInverse); + GetRotationMatrix(rot, GeometricRotation, chain[TransformationComp_GeometricRotation]); + GetRotationMatrix(rot, GeometricRotation, chain[TransformationComp_GeometricRotationInverse]); + chain[TransformationComp_GeometricRotationInverse].Inverse(); + } + + const aiVector3D& GeometricTranslation = PropertyGet(props, "GeometricTranslation", ok); + if (ok && GeometricTranslation.SquareLength() > zero_epsilon) { + chainBits = chainBits | (1 << TransformationComp_GeometricTranslation) | (1 << TransformationComp_GeometricTranslationInverse); + aiMatrix4x4::Translation(GeometricTranslation, chain[TransformationComp_GeometricTranslation]); + aiMatrix4x4::Translation(-GeometricTranslation, chain[TransformationComp_GeometricTranslationInverse]); + } + + // is_complex needs to be consistent with NeedsComplexTransformationChain() + // or the interplay between this code and the animation converter would + // not be guaranteed. + ai_assert(NeedsComplexTransformationChain(model) == ((chainBits & chainMaskComplex) != 0)); + + // now, if we have more than just Translation, Scaling and Rotation, + // we need to generate a full node chain to accommodate for assimp's + // lack to express pivots and offsets. + if ((chainBits & chainMaskComplex) && doc.Settings().preservePivots) { + FBXImporter::LogInfo("generating full transformation chain for node: " + name); + + // query the anim_chain_bits dictionary to find out which chain elements + // have associated node animation channels. These can not be dropped + // even if they have identity transform in bind pose. + NodeAnimBitMap::const_iterator it = node_anim_chain_bits.find(name); + const unsigned int anim_chain_bitmask = (it == node_anim_chain_bits.end() ? 0 : (*it).second); + + unsigned int bit = 0x1; + for (size_t i = 0; i < TransformationComp_MAXIMUM; ++i, bit <<= 1) { + const TransformationComp comp = static_cast(i); + + if ((chainBits & bit) == 0 && (anim_chain_bitmask & bit) == 0) { + continue; + } + + if (comp == TransformationComp_PostRotation) { + chain[i] = chain[i].Inverse(); + } + + aiNode* nd = new aiNode(); + nd->mName.Set(NameTransformationChainNode(name, comp)); + nd->mTransformation = chain[i]; + + // geometric inverses go in a post-node chain + if (comp == TransformationComp_GeometricScalingInverse || + comp == TransformationComp_GeometricRotationInverse || + comp == TransformationComp_GeometricTranslationInverse + ) { + post_output_nodes.push_back(nd); + } + else { + output_nodes.push_back(nd); + } + } + + ai_assert(output_nodes.size()); + return true; + } + + // else, we can just multiply the matrices together + aiNode* nd = new aiNode(); + output_nodes.push_back(nd); + + // name passed to the method is already unique + nd->mName.Set(name); + + for (const auto &transform : chain) { + nd->mTransformation = nd->mTransformation * transform; + } + return false; + } + + void FBXConverter::SetupNodeMetadata(const Model& model, aiNode& nd) + { + const PropertyTable& props = model.Props(); + DirectPropertyMap unparsedProperties = props.GetUnparsedProperties(); + + // create metadata on node + const std::size_t numStaticMetaData = 2; + aiMetadata* data = aiMetadata::Alloc(static_cast(unparsedProperties.size() + numStaticMetaData)); + nd.mMetaData = data; + int index = 0; + + // find user defined properties (3ds Max) + data->Set(index++, "UserProperties", aiString(PropertyGet(props, "UDP3DSMAX", ""))); + // preserve the info that a node was marked as Null node in the original file. + data->Set(index++, "IsNull", model.IsNull() ? true : false); + + // add unparsed properties to the node's metadata + for (const DirectPropertyMap::value_type& prop : unparsedProperties) { + // Interpret the property as a concrete type + if (const TypedProperty* interpreted = prop.second->As >()) { + data->Set(index++, prop.first, interpreted->Value()); + } + else if (const TypedProperty* interpreted = prop.second->As >()) { + data->Set(index++, prop.first, interpreted->Value()); + } + else if (const TypedProperty* interpreted = prop.second->As >()) { + data->Set(index++, prop.first, interpreted->Value()); + } + else if (const TypedProperty* interpreted = prop.second->As >()) { + data->Set(index++, prop.first, interpreted->Value()); + } + else if (const TypedProperty* interpreted = prop.second->As >()) { + data->Set(index++, prop.first, aiString(interpreted->Value())); + } + else if (const TypedProperty* interpreted = prop.second->As >()) { + data->Set(index++, prop.first, interpreted->Value()); + } + else { + ai_assert(false); + } + } + } + + void FBXConverter::ConvertModel(const Model& model, aiNode& nd, const aiMatrix4x4& node_global_transform) + { + const std::vector& geos = model.GetGeometry(); + + std::vector meshes; + meshes.reserve(geos.size()); + + for (const Geometry* geo : geos) { + + const MeshGeometry* const mesh = dynamic_cast(geo); + const LineGeometry* const line = dynamic_cast(geo); + if (mesh) { + const std::vector& indices = ConvertMesh(*mesh, model, node_global_transform, nd); + std::copy(indices.begin(), indices.end(), std::back_inserter(meshes)); + } + else if (line) { + const std::vector& indices = ConvertLine(*line, model, node_global_transform, nd); + std::copy(indices.begin(), indices.end(), std::back_inserter(meshes)); + } + else { + FBXImporter::LogWarn("ignoring unrecognized geometry: " + geo->Name()); + } + } + + if (meshes.size()) { + nd.mMeshes = new unsigned int[meshes.size()](); + nd.mNumMeshes = static_cast(meshes.size()); + + std::swap_ranges(meshes.begin(), meshes.end(), nd.mMeshes); + } + } + + std::vector FBXConverter::ConvertMesh(const MeshGeometry& mesh, const Model& model, + const aiMatrix4x4& node_global_transform, aiNode& nd) + { + std::vector temp; + + MeshMap::const_iterator it = meshes_converted.find(&mesh); + if (it != meshes_converted.end()) { + std::copy((*it).second.begin(), (*it).second.end(), std::back_inserter(temp)); + return temp; + } + + const std::vector& vertices = mesh.GetVertices(); + const std::vector& faces = mesh.GetFaceIndexCounts(); + if (vertices.empty() || faces.empty()) { + FBXImporter::LogWarn("ignoring empty geometry: " + mesh.Name()); + return temp; + } + + // one material per mesh maps easily to aiMesh. Multiple material + // meshes need to be split. + const MatIndexArray& mindices = mesh.GetMaterialIndices(); + if (doc.Settings().readMaterials && !mindices.empty()) { + const MatIndexArray::value_type base = mindices[0]; + for (MatIndexArray::value_type index : mindices) { + if (index != base) { + return ConvertMeshMultiMaterial(mesh, model, node_global_transform, nd); + } + } + } + + // faster code-path, just copy the data + temp.push_back(ConvertMeshSingleMaterial(mesh, model, node_global_transform, nd)); + return temp; + } + + std::vector FBXConverter::ConvertLine(const LineGeometry& line, const Model& model, + const aiMatrix4x4& node_global_transform, aiNode& nd) + { + std::vector temp; + + const std::vector& vertices = line.GetVertices(); + const std::vector& indices = line.GetIndices(); + if (vertices.empty() || indices.empty()) { + FBXImporter::LogWarn("ignoring empty line: " + line.Name()); + return temp; + } + + aiMesh* const out_mesh = SetupEmptyMesh(line, nd); + out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE; + + // copy vertices + out_mesh->mNumVertices = static_cast(vertices.size()); + out_mesh->mVertices = new aiVector3D[out_mesh->mNumVertices]; + std::copy(vertices.begin(), vertices.end(), out_mesh->mVertices); + + //Number of line segments (faces) is "Number of Points - Number of Endpoints" + //N.B.: Endpoints in FbxLine are denoted by negative indices. + //If such an Index is encountered, add 1 and multiply by -1 to get the real index. + unsigned int epcount = 0; + for (unsigned i = 0; i < indices.size(); i++) + { + if (indices[i] < 0) { + epcount++; + } + } + unsigned int pcount = static_cast( indices.size() ); + unsigned int scount = out_mesh->mNumFaces = pcount - epcount; + + aiFace* fac = out_mesh->mFaces = new aiFace[scount](); + for (unsigned int i = 0; i < pcount; ++i) { + if (indices[i] < 0) continue; + aiFace& f = *fac++; + f.mNumIndices = 2; //2 == aiPrimitiveType_LINE + f.mIndices = new unsigned int[2]; + f.mIndices[0] = indices[i]; + int segid = indices[(i + 1 == pcount ? 0 : i + 1)]; //If we have reached he last point, wrap around + f.mIndices[1] = (segid < 0 ? (segid + 1)*-1 : segid); //Convert EndPoint Index to normal Index + } + temp.push_back(static_cast(meshes.size() - 1)); + return temp; + } + + aiMesh* FBXConverter::SetupEmptyMesh(const Geometry& mesh, aiNode& nd) + { + aiMesh* const out_mesh = new aiMesh(); + meshes.push_back(out_mesh); + meshes_converted[&mesh].push_back(static_cast(meshes.size() - 1)); + + // set name + std::string name = mesh.Name(); + if (name.substr(0, 10) == "Geometry::") { + name = name.substr(10); + } + + if (name.length()) { + out_mesh->mName.Set(name); + } + else + { + out_mesh->mName = nd.mName; + } + + return out_mesh; + } + + unsigned int FBXConverter::ConvertMeshSingleMaterial(const MeshGeometry& mesh, const Model& model, + const aiMatrix4x4& node_global_transform, aiNode& nd) + { + const MatIndexArray& mindices = mesh.GetMaterialIndices(); + aiMesh* const out_mesh = SetupEmptyMesh(mesh, nd); + + const std::vector& vertices = mesh.GetVertices(); + const std::vector& faces = mesh.GetFaceIndexCounts(); + + // copy vertices + out_mesh->mNumVertices = static_cast(vertices.size()); + out_mesh->mVertices = new aiVector3D[vertices.size()]; + + std::copy(vertices.begin(), vertices.end(), out_mesh->mVertices); + + // generate dummy faces + out_mesh->mNumFaces = static_cast(faces.size()); + aiFace* fac = out_mesh->mFaces = new aiFace[faces.size()](); + + unsigned int cursor = 0; + for (unsigned int pcount : faces) { + aiFace& f = *fac++; + f.mNumIndices = pcount; + f.mIndices = new unsigned int[pcount]; + switch (pcount) + { + case 1: + out_mesh->mPrimitiveTypes |= aiPrimitiveType_POINT; + break; + case 2: + out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE; + break; + case 3: + out_mesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE; + break; + default: + out_mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON; + break; + } + for (unsigned int i = 0; i < pcount; ++i) { + f.mIndices[i] = cursor++; + } + } + + // copy normals + const std::vector& normals = mesh.GetNormals(); + if (normals.size()) { + ai_assert(normals.size() == vertices.size()); + + out_mesh->mNormals = new aiVector3D[vertices.size()]; + std::copy(normals.begin(), normals.end(), out_mesh->mNormals); + } + + // copy tangents - assimp requires both tangents and bitangents (binormals) + // to be present, or neither of them. Compute binormals from normals + // and tangents if needed. + const std::vector& tangents = mesh.GetTangents(); + const std::vector* binormals = &mesh.GetBinormals(); + + if (tangents.size()) { + std::vector tempBinormals; + if (!binormals->size()) { + if (normals.size()) { + tempBinormals.resize(normals.size()); + for (unsigned int i = 0; i < tangents.size(); ++i) { + tempBinormals[i] = normals[i] ^ tangents[i]; + } + + binormals = &tempBinormals; + } + else { + binormals = NULL; + } + } + + if (binormals) { + ai_assert(tangents.size() == vertices.size()); + ai_assert(binormals->size() == vertices.size()); + + out_mesh->mTangents = new aiVector3D[vertices.size()]; + std::copy(tangents.begin(), tangents.end(), out_mesh->mTangents); + + out_mesh->mBitangents = new aiVector3D[vertices.size()]; + std::copy(binormals->begin(), binormals->end(), out_mesh->mBitangents); + } + } + + // copy texture coords + for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) { + const std::vector& uvs = mesh.GetTextureCoords(i); + if (uvs.empty()) { + break; + } + + aiVector3D* out_uv = out_mesh->mTextureCoords[i] = new aiVector3D[vertices.size()]; + for (const aiVector2D& v : uvs) { + *out_uv++ = aiVector3D(v.x, v.y, 0.0f); + } + + out_mesh->mNumUVComponents[i] = 2; + } + + // copy vertex colors + for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i) { + const std::vector& colors = mesh.GetVertexColors(i); + if (colors.empty()) { + break; + } + + out_mesh->mColors[i] = new aiColor4D[vertices.size()]; + std::copy(colors.begin(), colors.end(), out_mesh->mColors[i]); + } + + if (!doc.Settings().readMaterials || mindices.empty()) { + FBXImporter::LogError("no material assigned to mesh, setting default material"); + out_mesh->mMaterialIndex = GetDefaultMaterial(); + } + else { + ConvertMaterialForMesh(out_mesh, model, mesh, mindices[0]); + } + + if (doc.Settings().readWeights && mesh.DeformerSkin() != NULL) { + ConvertWeights(out_mesh, model, mesh, node_global_transform, NO_MATERIAL_SEPARATION); + } + + std::vector animMeshes; + for (const BlendShape* blendShape : mesh.GetBlendShapes()) { + for (const BlendShapeChannel* blendShapeChannel : blendShape->BlendShapeChannels()) { + const std::vector& shapeGeometries = blendShapeChannel->GetShapeGeometries(); + for (size_t i = 0; i < shapeGeometries.size(); i++) { + aiAnimMesh *animMesh = aiCreateAnimMesh(out_mesh); + const ShapeGeometry* shapeGeometry = shapeGeometries.at(i); + const std::vector& vertices = shapeGeometry->GetVertices(); + const std::vector& normals = shapeGeometry->GetNormals(); + const std::vector& indices = shapeGeometry->GetIndices(); + animMesh->mName.Set(FixAnimMeshName(shapeGeometry->Name())); + for (size_t j = 0; j < indices.size(); j++) { + unsigned int index = indices.at(j); + aiVector3D vertex = vertices.at(j); + aiVector3D normal = normals.at(j); + unsigned int count = 0; + const unsigned int* outIndices = mesh.ToOutputVertexIndex(index, count); + for (unsigned int k = 0; k < count; k++) { + unsigned int index = outIndices[k]; + animMesh->mVertices[index] += vertex; + if (animMesh->mNormals != nullptr) { + animMesh->mNormals[index] += normal; + animMesh->mNormals[index].NormalizeSafe(); + } + } + } + animMesh->mWeight = shapeGeometries.size() > 1 ? blendShapeChannel->DeformPercent() / 100.0f : 1.0f; + animMeshes.push_back(animMesh); + } + } + } + const size_t numAnimMeshes = animMeshes.size(); + if (numAnimMeshes > 0) { + out_mesh->mNumAnimMeshes = static_cast(numAnimMeshes); + out_mesh->mAnimMeshes = new aiAnimMesh*[numAnimMeshes]; + for (size_t i = 0; i < numAnimMeshes; i++) { + out_mesh->mAnimMeshes[i] = animMeshes.at(i); + } + } + return static_cast(meshes.size() - 1); + } + + std::vector FBXConverter::ConvertMeshMultiMaterial(const MeshGeometry& mesh, const Model& model, + const aiMatrix4x4& node_global_transform, aiNode& nd) + { + const MatIndexArray& mindices = mesh.GetMaterialIndices(); + ai_assert(mindices.size()); + + std::set had; + std::vector indices; + + for (MatIndexArray::value_type index : mindices) { + if (had.find(index) == had.end()) { + + indices.push_back(ConvertMeshMultiMaterial(mesh, model, index, node_global_transform, nd)); + had.insert(index); + } + } + + return indices; + } + + unsigned int FBXConverter::ConvertMeshMultiMaterial(const MeshGeometry& mesh, const Model& model, + MatIndexArray::value_type index, + const aiMatrix4x4& node_global_transform, + aiNode& nd) + { + aiMesh* const out_mesh = SetupEmptyMesh(mesh, nd); + + const MatIndexArray& mindices = mesh.GetMaterialIndices(); + const std::vector& vertices = mesh.GetVertices(); + const std::vector& faces = mesh.GetFaceIndexCounts(); + + const bool process_weights = doc.Settings().readWeights && mesh.DeformerSkin() != NULL; + + unsigned int count_faces = 0; + unsigned int count_vertices = 0; + + // count faces + std::vector::const_iterator itf = faces.begin(); + for (MatIndexArray::const_iterator it = mindices.begin(), + end = mindices.end(); it != end; ++it, ++itf) + { + if ((*it) != index) { + continue; + } + ++count_faces; + count_vertices += *itf; + } + + ai_assert(count_faces); + ai_assert(count_vertices); + + // mapping from output indices to DOM indexing, needed to resolve weights or blendshapes + std::vector reverseMapping; + std::map translateIndexMap; + if (process_weights || mesh.GetBlendShapes().size() > 0) { + reverseMapping.resize(count_vertices); + } + + // allocate output data arrays, but don't fill them yet + out_mesh->mNumVertices = count_vertices; + out_mesh->mVertices = new aiVector3D[count_vertices]; + + out_mesh->mNumFaces = count_faces; + aiFace* fac = out_mesh->mFaces = new aiFace[count_faces](); + + + // allocate normals + const std::vector& normals = mesh.GetNormals(); + if (normals.size()) { + ai_assert(normals.size() == vertices.size()); + out_mesh->mNormals = new aiVector3D[vertices.size()]; + } + + // allocate tangents, binormals. + const std::vector& tangents = mesh.GetTangents(); + const std::vector* binormals = &mesh.GetBinormals(); + std::vector tempBinormals; + + if (tangents.size()) { + if (!binormals->size()) { + if (normals.size()) { + // XXX this computes the binormals for the entire mesh, not only + // the part for which we need them. + tempBinormals.resize(normals.size()); + for (unsigned int i = 0; i < tangents.size(); ++i) { + tempBinormals[i] = normals[i] ^ tangents[i]; + } + + binormals = &tempBinormals; + } + else { + binormals = NULL; + } + } + + if (binormals) { + ai_assert(tangents.size() == vertices.size() && binormals->size() == vertices.size()); + + out_mesh->mTangents = new aiVector3D[vertices.size()]; + out_mesh->mBitangents = new aiVector3D[vertices.size()]; + } + } + + // allocate texture coords + unsigned int num_uvs = 0; + for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i, ++num_uvs) { + const std::vector& uvs = mesh.GetTextureCoords(i); + if (uvs.empty()) { + break; + } + + out_mesh->mTextureCoords[i] = new aiVector3D[vertices.size()]; + out_mesh->mNumUVComponents[i] = 2; + } + + // allocate vertex colors + unsigned int num_vcs = 0; + for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i, ++num_vcs) { + const std::vector& colors = mesh.GetVertexColors(i); + if (colors.empty()) { + break; + } + + out_mesh->mColors[i] = new aiColor4D[vertices.size()]; + } + + unsigned int cursor = 0, in_cursor = 0; + + itf = faces.begin(); + for (MatIndexArray::const_iterator it = mindices.begin(), end = mindices.end(); it != end; ++it, ++itf) + { + const unsigned int pcount = *itf; + if ((*it) != index) { + in_cursor += pcount; + continue; + } + + aiFace& f = *fac++; + + f.mNumIndices = pcount; + f.mIndices = new unsigned int[pcount]; + switch (pcount) + { + case 1: + out_mesh->mPrimitiveTypes |= aiPrimitiveType_POINT; + break; + case 2: + out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE; + break; + case 3: + out_mesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE; + break; + default: + out_mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON; + break; + } + for (unsigned int i = 0; i < pcount; ++i, ++cursor, ++in_cursor) { + f.mIndices[i] = cursor; + + if (reverseMapping.size()) { + reverseMapping[cursor] = in_cursor; + translateIndexMap[in_cursor] = cursor; + } + + out_mesh->mVertices[cursor] = vertices[in_cursor]; + + if (out_mesh->mNormals) { + out_mesh->mNormals[cursor] = normals[in_cursor]; + } + + if (out_mesh->mTangents) { + out_mesh->mTangents[cursor] = tangents[in_cursor]; + out_mesh->mBitangents[cursor] = (*binormals)[in_cursor]; + } + + for (unsigned int j = 0; j < num_uvs; ++j) { + const std::vector& uvs = mesh.GetTextureCoords(j); + out_mesh->mTextureCoords[j][cursor] = aiVector3D(uvs[in_cursor].x, uvs[in_cursor].y, 0.0f); + } + + for (unsigned int j = 0; j < num_vcs; ++j) { + const std::vector& cols = mesh.GetVertexColors(j); + out_mesh->mColors[j][cursor] = cols[in_cursor]; + } + } + } + + ConvertMaterialForMesh(out_mesh, model, mesh, index); + + if (process_weights) { + ConvertWeights(out_mesh, model, mesh, node_global_transform, index, &reverseMapping); + } + + std::vector animMeshes; + for (const BlendShape* blendShape : mesh.GetBlendShapes()) { + for (const BlendShapeChannel* blendShapeChannel : blendShape->BlendShapeChannels()) { + const std::vector& shapeGeometries = blendShapeChannel->GetShapeGeometries(); + for (size_t i = 0; i < shapeGeometries.size(); i++) { + aiAnimMesh* animMesh = aiCreateAnimMesh(out_mesh); + const ShapeGeometry* shapeGeometry = shapeGeometries.at(i); + const std::vector& vertices = shapeGeometry->GetVertices(); + const std::vector& normals = shapeGeometry->GetNormals(); + const std::vector& indices = shapeGeometry->GetIndices(); + animMesh->mName.Set(FixAnimMeshName(shapeGeometry->Name())); + for (size_t j = 0; j < indices.size(); j++) { + unsigned int index = indices.at(j); + aiVector3D vertex = vertices.at(j); + aiVector3D normal = normals.at(j); + unsigned int count = 0; + const unsigned int* outIndices = mesh.ToOutputVertexIndex(index, count); + for (unsigned int k = 0; k < count; k++) { + unsigned int outIndex = outIndices[k]; + if (translateIndexMap.find(outIndex) == translateIndexMap.end()) + continue; + unsigned int index = translateIndexMap[outIndex]; + animMesh->mVertices[index] += vertex; + if (animMesh->mNormals != nullptr) { + animMesh->mNormals[index] += normal; + animMesh->mNormals[index].NormalizeSafe(); + } + } + } + animMesh->mWeight = shapeGeometries.size() > 1 ? blendShapeChannel->DeformPercent() / 100.0f : 1.0f; + animMeshes.push_back(animMesh); + } + } + } + + const size_t numAnimMeshes = animMeshes.size(); + if (numAnimMeshes > 0) { + out_mesh->mNumAnimMeshes = static_cast(numAnimMeshes); + out_mesh->mAnimMeshes = new aiAnimMesh*[numAnimMeshes]; + for (size_t i = 0; i < numAnimMeshes; i++) { + out_mesh->mAnimMeshes[i] = animMeshes.at(i); + } + } + + return static_cast(meshes.size() - 1); + } + + void FBXConverter::ConvertWeights(aiMesh* out, const Model& model, const MeshGeometry& geo, + const aiMatrix4x4& node_global_transform, + unsigned int materialIndex, + std::vector* outputVertStartIndices) + { + ai_assert(geo.DeformerSkin()); + + std::vector out_indices; + std::vector index_out_indices; + std::vector count_out_indices; + + const Skin& sk = *geo.DeformerSkin(); + + std::vector bones; + bones.reserve(sk.Clusters().size()); + + const bool no_mat_check = materialIndex == NO_MATERIAL_SEPARATION; + ai_assert(no_mat_check || outputVertStartIndices); + + try { + + for (const Cluster* cluster : sk.Clusters()) { + ai_assert(cluster); + + const WeightIndexArray& indices = cluster->GetIndices(); + + const MatIndexArray& mats = geo.GetMaterialIndices(); + + const size_t no_index_sentinel = std::numeric_limits::max(); + + count_out_indices.clear(); + index_out_indices.clear(); + out_indices.clear(); + + // now check if *any* of these weights is contained in the output mesh, + // taking notes so we don't need to do it twice. + for (WeightIndexArray::value_type index : indices) { + + unsigned int count = 0; + const unsigned int* const out_idx = geo.ToOutputVertexIndex(index, count); + // ToOutputVertexIndex only returns NULL if index is out of bounds + // which should never happen + ai_assert(out_idx != NULL); + + index_out_indices.push_back(no_index_sentinel); + count_out_indices.push_back(0); + + for (unsigned int i = 0; i < count; ++i) { + if (no_mat_check || static_cast(mats[geo.FaceForVertexIndex(out_idx[i])]) == materialIndex) { + + if (index_out_indices.back() == no_index_sentinel) { + index_out_indices.back() = out_indices.size(); + } + + if (no_mat_check) { + out_indices.push_back(out_idx[i]); + } else { + // this extra lookup is in O(logn), so the entire algorithm becomes O(nlogn) + const std::vector::iterator it = std::lower_bound( + outputVertStartIndices->begin(), + outputVertStartIndices->end(), + out_idx[i] + ); + + out_indices.push_back(std::distance(outputVertStartIndices->begin(), it)); + } + + ++count_out_indices.back(); + } + } + } + + // if we found at least one, generate the output bones + // XXX this could be heavily simplified by collecting the bone + // data in a single step. + ConvertCluster(bones, model, *cluster, out_indices, index_out_indices, + count_out_indices, node_global_transform); + } + } + catch (std::exception&) { + std::for_each(bones.begin(), bones.end(), Util::delete_fun()); + throw; + } + + if (bones.empty()) { + return; + } + + out->mBones = new aiBone*[bones.size()](); + out->mNumBones = static_cast(bones.size()); + + std::swap_ranges(bones.begin(), bones.end(), out->mBones); + } + + void FBXConverter::ConvertCluster(std::vector& bones, const Model& /*model*/, const Cluster& cl, + std::vector& out_indices, + std::vector& index_out_indices, + std::vector& count_out_indices, + const aiMatrix4x4& node_global_transform) + { + + aiBone* const bone = new aiBone(); + bones.push_back(bone); + + bone->mName = FixNodeName(cl.TargetNode()->Name()); + + bone->mOffsetMatrix = cl.TransformLink(); + bone->mOffsetMatrix.Inverse(); + + bone->mOffsetMatrix = bone->mOffsetMatrix * node_global_transform; + + bone->mNumWeights = static_cast(out_indices.size()); + aiVertexWeight* cursor = bone->mWeights = new aiVertexWeight[out_indices.size()]; + + const size_t no_index_sentinel = std::numeric_limits::max(); + const WeightArray& weights = cl.GetWeights(); + + const size_t c = index_out_indices.size(); + for (size_t i = 0; i < c; ++i) { + const size_t index_index = index_out_indices[i]; + + if (index_index == no_index_sentinel) { + continue; + } + + const size_t cc = count_out_indices[i]; + for (size_t j = 0; j < cc; ++j) { + aiVertexWeight& out_weight = *cursor++; + + out_weight.mVertexId = static_cast(out_indices[index_index + j]); + out_weight.mWeight = weights[i]; + } + } + } + + void FBXConverter::ConvertMaterialForMesh(aiMesh* out, const Model& model, const MeshGeometry& geo, + MatIndexArray::value_type materialIndex) + { + // locate source materials for this mesh + const std::vector& mats = model.GetMaterials(); + if (static_cast(materialIndex) >= mats.size() || materialIndex < 0) { + FBXImporter::LogError("material index out of bounds, setting default material"); + out->mMaterialIndex = GetDefaultMaterial(); + return; + } + + const Material* const mat = mats[materialIndex]; + MaterialMap::const_iterator it = materials_converted.find(mat); + if (it != materials_converted.end()) { + out->mMaterialIndex = (*it).second; + return; + } + + out->mMaterialIndex = ConvertMaterial(*mat, &geo); + materials_converted[mat] = out->mMaterialIndex; + } + + unsigned int FBXConverter::GetDefaultMaterial() + { + if (defaultMaterialIndex) { + return defaultMaterialIndex - 1; + } + + aiMaterial* out_mat = new aiMaterial(); + materials.push_back(out_mat); + + const aiColor3D diffuse = aiColor3D(0.8f, 0.8f, 0.8f); + out_mat->AddProperty(&diffuse, 1, AI_MATKEY_COLOR_DIFFUSE); + + aiString s; + s.Set(AI_DEFAULT_MATERIAL_NAME); + + out_mat->AddProperty(&s, AI_MATKEY_NAME); + + defaultMaterialIndex = static_cast(materials.size()); + return defaultMaterialIndex - 1; + } + + + unsigned int FBXConverter::ConvertMaterial(const Material& material, const MeshGeometry* const mesh) + { + const PropertyTable& props = material.Props(); + + // generate empty output material + aiMaterial* out_mat = new aiMaterial(); + materials_converted[&material] = static_cast(materials.size()); + + materials.push_back(out_mat); + + aiString str; + + // strip Material:: prefix + std::string name = material.Name(); + if (name.substr(0, 10) == "Material::") { + name = name.substr(10); + } + + // set material name if not empty - this could happen + // and there should be no key for it in this case. + if (name.length()) { + str.Set(name); + out_mat->AddProperty(&str, AI_MATKEY_NAME); + } + + // Set the shading mode as best we can: The FBX specification only mentions Lambert and Phong, and only Phong is mentioned in Assimp's aiShadingMode enum. + if (material.GetShadingModel() == "phong") + { + aiShadingMode shadingMode = aiShadingMode_Phong; + out_mat->AddProperty(&shadingMode, 1, AI_MATKEY_SHADING_MODEL); + } + + // shading stuff and colors + SetShadingPropertiesCommon(out_mat, props); + SetShadingPropertiesRaw( out_mat, props, material.Textures(), mesh ); + + // texture assignments + SetTextureProperties(out_mat, material.Textures(), mesh); + SetTextureProperties(out_mat, material.LayeredTextures(), mesh); + + return static_cast(materials.size() - 1); + } + + unsigned int FBXConverter::ConvertVideo(const Video& video) + { + // generate empty output texture + aiTexture* out_tex = new aiTexture(); + textures.push_back(out_tex); + + // assuming the texture is compressed + out_tex->mWidth = static_cast(video.ContentLength()); // total data size + out_tex->mHeight = 0; // fixed to 0 + + // steal the data from the Video to avoid an additional copy + out_tex->pcData = reinterpret_cast(const_cast(video).RelinquishContent()); + + // try to extract a hint from the file extension + const std::string& filename = video.RelativeFilename().empty() ? video.FileName() : video.RelativeFilename(); + std::string ext = BaseImporter::GetExtension(filename); + + if (ext == "jpeg") { + ext = "jpg"; + } + + if (ext.size() <= 3) { + memcpy(out_tex->achFormatHint, ext.c_str(), ext.size()); + } + + out_tex->mFilename.Set(filename.c_str()); + + return static_cast(textures.size() - 1); + } + + aiString FBXConverter::GetTexturePath(const Texture* tex) + { + aiString path; + path.Set(tex->RelativeFilename()); + + const Video* media = tex->Media(); + if (media != nullptr) { + bool textureReady = false; //tells if our texture is ready (if it was loaded or if it was found) + unsigned int index; + + VideoMap::const_iterator it = textures_converted.find(media); + if (it != textures_converted.end()) { + index = (*it).second; + textureReady = true; + } + else { + if (media->ContentLength() > 0) { + index = ConvertVideo(*media); + textures_converted[media] = index; + textureReady = true; + } + } + + // setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture), if the texture is ready + if (doc.Settings().useLegacyEmbeddedTextureNaming) { + if (textureReady) { + // TODO: check the possibility of using the flag "AI_CONFIG_IMPORT_FBX_EMBEDDED_TEXTURES_LEGACY_NAMING" + // In FBX files textures are now stored internally by Assimp with their filename included + // Now Assimp can lookup through the loaded textures after all data is processed + // We need to load all textures before referencing them, as FBX file format order may reference a texture before loading it + // This may occur on this case too, it has to be studied + path.data[0] = '*'; + path.length = 1 + ASSIMP_itoa10(path.data + 1, MAXLEN - 1, index); + } + } + } + + return path; + } + + void FBXConverter::TrySetTextureProperties(aiMaterial* out_mat, const TextureMap& textures, + const std::string& propName, + aiTextureType target, const MeshGeometry* const mesh) { + TextureMap::const_iterator it = textures.find(propName); + if (it == textures.end()) { + return; + } + + const Texture* const tex = (*it).second; + if (tex != 0) + { + aiString path = GetTexturePath(tex); + out_mat->AddProperty(&path, _AI_MATKEY_TEXTURE_BASE, target, 0); + + aiUVTransform uvTrafo; + // XXX handle all kinds of UV transformations + uvTrafo.mScaling = tex->UVScaling(); + uvTrafo.mTranslation = tex->UVTranslation(); + out_mat->AddProperty(&uvTrafo, 1, _AI_MATKEY_UVTRANSFORM_BASE, target, 0); + + const PropertyTable& props = tex->Props(); + + int uvIndex = 0; + + bool ok; + const std::string& uvSet = PropertyGet(props, "UVSet", ok); + if (ok) { + // "default" is the name which usually appears in the FbxFileTexture template + if (uvSet != "default" && uvSet.length()) { + // this is a bit awkward - we need to find a mesh that uses this + // material and scan its UV channels for the given UV name because + // assimp references UV channels by index, not by name. + + // XXX: the case that UV channels may appear in different orders + // in meshes is unhandled. A possible solution would be to sort + // the UV channels alphabetically, but this would have the side + // effect that the primary (first) UV channel would sometimes + // be moved, causing trouble when users read only the first + // UV channel and ignore UV channel assignments altogether. + + const unsigned int matIndex = static_cast(std::distance(materials.begin(), + std::find(materials.begin(), materials.end(), out_mat) + )); + + + uvIndex = -1; + if (!mesh) + { + for (const MeshMap::value_type& v : meshes_converted) { + const MeshGeometry* const meshGeom = dynamic_cast (v.first); + if (!meshGeom) { + continue; + } + + const MatIndexArray& mats = meshGeom->GetMaterialIndices(); + if (std::find(mats.begin(), mats.end(), matIndex) == mats.end()) { + continue; + } + + int index = -1; + for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) { + if (meshGeom->GetTextureCoords(i).empty()) { + break; + } + const std::string& name = meshGeom->GetTextureCoordChannelName(i); + if (name == uvSet) { + index = static_cast(i); + break; + } + } + if (index == -1) { + FBXImporter::LogWarn("did not find UV channel named " + uvSet + " in a mesh using this material"); + continue; + } + + if (uvIndex == -1) { + uvIndex = index; + } + else { + FBXImporter::LogWarn("the UV channel named " + uvSet + + " appears at different positions in meshes, results will be wrong"); + } + } + } + else + { + int index = -1; + for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) { + if (mesh->GetTextureCoords(i).empty()) { + break; + } + const std::string& name = mesh->GetTextureCoordChannelName(i); + if (name == uvSet) { + index = static_cast(i); + break; + } + } + if (index == -1) { + FBXImporter::LogWarn("did not find UV channel named " + uvSet + " in a mesh using this material"); + } + + if (uvIndex == -1) { + uvIndex = index; + } + } + + if (uvIndex == -1) { + FBXImporter::LogWarn("failed to resolve UV channel " + uvSet + ", using first UV channel"); + uvIndex = 0; + } + } + } + + out_mat->AddProperty(&uvIndex, 1, _AI_MATKEY_UVWSRC_BASE, target, 0); + } + } + + void FBXConverter::TrySetTextureProperties(aiMaterial* out_mat, const LayeredTextureMap& layeredTextures, + const std::string& propName, + aiTextureType target, const MeshGeometry* const mesh) { + LayeredTextureMap::const_iterator it = layeredTextures.find(propName); + if (it == layeredTextures.end()) { + return; + } + + int texCount = (*it).second->textureCount(); + + // Set the blend mode for layered textures + int blendmode = (*it).second->GetBlendMode(); + out_mat->AddProperty(&blendmode, 1, _AI_MATKEY_TEXOP_BASE, target, 0); + + for (int texIndex = 0; texIndex < texCount; texIndex++) { + + const Texture* const tex = (*it).second->getTexture(texIndex); + + aiString path = GetTexturePath(tex); + out_mat->AddProperty(&path, _AI_MATKEY_TEXTURE_BASE, target, texIndex); + + aiUVTransform uvTrafo; + // XXX handle all kinds of UV transformations + uvTrafo.mScaling = tex->UVScaling(); + uvTrafo.mTranslation = tex->UVTranslation(); + out_mat->AddProperty(&uvTrafo, 1, _AI_MATKEY_UVTRANSFORM_BASE, target, texIndex); + + const PropertyTable& props = tex->Props(); + + int uvIndex = 0; + + bool ok; + const std::string& uvSet = PropertyGet(props, "UVSet", ok); + if (ok) { + // "default" is the name which usually appears in the FbxFileTexture template + if (uvSet != "default" && uvSet.length()) { + // this is a bit awkward - we need to find a mesh that uses this + // material and scan its UV channels for the given UV name because + // assimp references UV channels by index, not by name. + + // XXX: the case that UV channels may appear in different orders + // in meshes is unhandled. A possible solution would be to sort + // the UV channels alphabetically, but this would have the side + // effect that the primary (first) UV channel would sometimes + // be moved, causing trouble when users read only the first + // UV channel and ignore UV channel assignments altogether. + + const unsigned int matIndex = static_cast(std::distance(materials.begin(), + std::find(materials.begin(), materials.end(), out_mat) + )); + + uvIndex = -1; + if (!mesh) + { + for (const MeshMap::value_type& v : meshes_converted) { + const MeshGeometry* const meshGeom = dynamic_cast (v.first); + if (!meshGeom) { + continue; + } + + const MatIndexArray& mats = meshGeom->GetMaterialIndices(); + if (std::find(mats.begin(), mats.end(), matIndex) == mats.end()) { + continue; + } + + int index = -1; + for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) { + if (meshGeom->GetTextureCoords(i).empty()) { + break; + } + const std::string& name = meshGeom->GetTextureCoordChannelName(i); + if (name == uvSet) { + index = static_cast(i); + break; + } + } + if (index == -1) { + FBXImporter::LogWarn("did not find UV channel named " + uvSet + " in a mesh using this material"); + continue; + } + + if (uvIndex == -1) { + uvIndex = index; + } + else { + FBXImporter::LogWarn("the UV channel named " + uvSet + + " appears at different positions in meshes, results will be wrong"); + } + } + } + else + { + int index = -1; + for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) { + if (mesh->GetTextureCoords(i).empty()) { + break; + } + const std::string& name = mesh->GetTextureCoordChannelName(i); + if (name == uvSet) { + index = static_cast(i); + break; + } + } + if (index == -1) { + FBXImporter::LogWarn("did not find UV channel named " + uvSet + " in a mesh using this material"); + } + + if (uvIndex == -1) { + uvIndex = index; + } + } + + if (uvIndex == -1) { + FBXImporter::LogWarn("failed to resolve UV channel " + uvSet + ", using first UV channel"); + uvIndex = 0; + } + } + } + + out_mat->AddProperty(&uvIndex, 1, _AI_MATKEY_UVWSRC_BASE, target, texIndex); + } + } + + void FBXConverter::SetTextureProperties(aiMaterial* out_mat, const TextureMap& textures, const MeshGeometry* const mesh) + { + TrySetTextureProperties(out_mat, textures, "DiffuseColor", aiTextureType_DIFFUSE, mesh); + TrySetTextureProperties(out_mat, textures, "AmbientColor", aiTextureType_AMBIENT, mesh); + TrySetTextureProperties(out_mat, textures, "EmissiveColor", aiTextureType_EMISSIVE, mesh); + TrySetTextureProperties(out_mat, textures, "SpecularColor", aiTextureType_SPECULAR, mesh); + TrySetTextureProperties(out_mat, textures, "SpecularFactor", aiTextureType_SPECULAR, mesh); + TrySetTextureProperties(out_mat, textures, "TransparentColor", aiTextureType_OPACITY, mesh); + TrySetTextureProperties(out_mat, textures, "ReflectionColor", aiTextureType_REFLECTION, mesh); + TrySetTextureProperties(out_mat, textures, "DisplacementColor", aiTextureType_DISPLACEMENT, mesh); + TrySetTextureProperties(out_mat, textures, "NormalMap", aiTextureType_NORMALS, mesh); + TrySetTextureProperties(out_mat, textures, "Bump", aiTextureType_HEIGHT, mesh); + TrySetTextureProperties(out_mat, textures, "ShininessExponent", aiTextureType_SHININESS, mesh); + TrySetTextureProperties( out_mat, textures, "TransparencyFactor", aiTextureType_OPACITY, mesh ); + TrySetTextureProperties( out_mat, textures, "EmissiveFactor", aiTextureType_EMISSIVE, mesh ); + //Maya counterparts + TrySetTextureProperties(out_mat, textures, "Maya|DiffuseTexture", aiTextureType_DIFFUSE, mesh); + TrySetTextureProperties(out_mat, textures, "Maya|NormalTexture", aiTextureType_NORMALS, mesh); + TrySetTextureProperties(out_mat, textures, "Maya|SpecularTexture", aiTextureType_SPECULAR, mesh); + TrySetTextureProperties(out_mat, textures, "Maya|FalloffTexture", aiTextureType_OPACITY, mesh); + TrySetTextureProperties(out_mat, textures, "Maya|ReflectionMapTexture", aiTextureType_REFLECTION, mesh); + + // Maya PBR + TrySetTextureProperties(out_mat, textures, "Maya|baseColor|file", aiTextureType_BASE_COLOR, mesh); + TrySetTextureProperties(out_mat, textures, "Maya|normalCamera|file", aiTextureType_NORMAL_CAMERA, mesh); + TrySetTextureProperties(out_mat, textures, "Maya|emissionColor|file", aiTextureType_EMISSION_COLOR, mesh); + TrySetTextureProperties(out_mat, textures, "Maya|metalness|file", aiTextureType_METALNESS, mesh); + TrySetTextureProperties(out_mat, textures, "Maya|diffuseRoughness|file", aiTextureType_DIFFUSE_ROUGHNESS, mesh); + + // Maya stingray + TrySetTextureProperties(out_mat, textures, "Maya|TEX_color_map|file", aiTextureType_BASE_COLOR, mesh); + TrySetTextureProperties(out_mat, textures, "Maya|TEX_normal_map|file", aiTextureType_NORMAL_CAMERA, mesh); + TrySetTextureProperties(out_mat, textures, "Maya|TEX_emissive_map|file", aiTextureType_EMISSION_COLOR, mesh); + TrySetTextureProperties(out_mat, textures, "Maya|TEX_metallic_map|file", aiTextureType_METALNESS, mesh); + TrySetTextureProperties(out_mat, textures, "Maya|TEX_roughness_map|file", aiTextureType_DIFFUSE_ROUGHNESS, mesh); + TrySetTextureProperties(out_mat, textures, "Maya|TEX_ao_map|file", aiTextureType_AMBIENT_OCCLUSION, mesh); + } + + void FBXConverter::SetTextureProperties(aiMaterial* out_mat, const LayeredTextureMap& layeredTextures, const MeshGeometry* const mesh) + { + TrySetTextureProperties(out_mat, layeredTextures, "DiffuseColor", aiTextureType_DIFFUSE, mesh); + TrySetTextureProperties(out_mat, layeredTextures, "AmbientColor", aiTextureType_AMBIENT, mesh); + TrySetTextureProperties(out_mat, layeredTextures, "EmissiveColor", aiTextureType_EMISSIVE, mesh); + TrySetTextureProperties(out_mat, layeredTextures, "SpecularColor", aiTextureType_SPECULAR, mesh); + TrySetTextureProperties(out_mat, layeredTextures, "SpecularFactor", aiTextureType_SPECULAR, mesh); + TrySetTextureProperties(out_mat, layeredTextures, "TransparentColor", aiTextureType_OPACITY, mesh); + TrySetTextureProperties(out_mat, layeredTextures, "ReflectionColor", aiTextureType_REFLECTION, mesh); + TrySetTextureProperties(out_mat, layeredTextures, "DisplacementColor", aiTextureType_DISPLACEMENT, mesh); + TrySetTextureProperties(out_mat, layeredTextures, "NormalMap", aiTextureType_NORMALS, mesh); + TrySetTextureProperties(out_mat, layeredTextures, "Bump", aiTextureType_HEIGHT, mesh); + TrySetTextureProperties(out_mat, layeredTextures, "ShininessExponent", aiTextureType_SHININESS, mesh); + TrySetTextureProperties( out_mat, layeredTextures, "EmissiveFactor", aiTextureType_EMISSIVE, mesh ); + TrySetTextureProperties( out_mat, layeredTextures, "TransparencyFactor", aiTextureType_OPACITY, mesh ); + } + + aiColor3D FBXConverter::GetColorPropertyFactored(const PropertyTable& props, const std::string& colorName, + const std::string& factorName, bool& result, bool useTemplate) + { + result = true; + + bool ok; + aiVector3D BaseColor = PropertyGet(props, colorName, ok, useTemplate); + if (!ok) { + result = false; + return aiColor3D(0.0f, 0.0f, 0.0f); + } + + // if no factor name, return the colour as is + if (factorName.empty()) { + return aiColor3D(BaseColor.x, BaseColor.y, BaseColor.z); + } + + // otherwise it should be multiplied by the factor, if found. + float factor = PropertyGet(props, factorName, ok, useTemplate); + if (ok) { + BaseColor *= factor; + } + return aiColor3D(BaseColor.x, BaseColor.y, BaseColor.z); + } + + aiColor3D FBXConverter::GetColorPropertyFromMaterial(const PropertyTable& props, const std::string& baseName, + bool& result) + { + return GetColorPropertyFactored(props, baseName + "Color", baseName + "Factor", result, true); + } + + aiColor3D FBXConverter::GetColorProperty(const PropertyTable& props, const std::string& colorName, + bool& result, bool useTemplate) + { + result = true; + bool ok; + const aiVector3D& ColorVec = PropertyGet(props, colorName, ok, useTemplate); + if (!ok) { + result = false; + return aiColor3D(0.0f, 0.0f, 0.0f); + } + return aiColor3D(ColorVec.x, ColorVec.y, ColorVec.z); + } + + void FBXConverter::SetShadingPropertiesCommon(aiMaterial* out_mat, const PropertyTable& props) + { + // Set shading properties. + // Modern FBX Files have two separate systems for defining these, + // with only the more comprehensive one described in the property template. + // Likely the other values are a legacy system, + // which is still always exported by the official FBX SDK. + // + // Blender's FBX import and export mostly ignore this legacy system, + // and as we only support recent versions of FBX anyway, we can do the same. + bool ok; + + const aiColor3D& Diffuse = GetColorPropertyFromMaterial(props, "Diffuse", ok); + if (ok) { + out_mat->AddProperty(&Diffuse, 1, AI_MATKEY_COLOR_DIFFUSE); + } + + const aiColor3D& Emissive = GetColorPropertyFromMaterial(props, "Emissive", ok); + if (ok) { + out_mat->AddProperty(&Emissive, 1, AI_MATKEY_COLOR_EMISSIVE); + } + + const aiColor3D& Ambient = GetColorPropertyFromMaterial(props, "Ambient", ok); + if (ok) { + out_mat->AddProperty(&Ambient, 1, AI_MATKEY_COLOR_AMBIENT); + } + + // we store specular factor as SHININESS_STRENGTH, so just get the color + const aiColor3D& Specular = GetColorProperty(props, "SpecularColor", ok, true); + if (ok) { + out_mat->AddProperty(&Specular, 1, AI_MATKEY_COLOR_SPECULAR); + } + + // and also try to get SHININESS_STRENGTH + const float SpecularFactor = PropertyGet(props, "SpecularFactor", ok, true); + if (ok) { + out_mat->AddProperty(&SpecularFactor, 1, AI_MATKEY_SHININESS_STRENGTH); + } + + // and the specular exponent + const float ShininessExponent = PropertyGet(props, "ShininessExponent", ok); + if (ok) { + out_mat->AddProperty(&ShininessExponent, 1, AI_MATKEY_SHININESS); + } + + // TransparentColor / TransparencyFactor... gee thanks FBX :rolleyes: + const aiColor3D& Transparent = GetColorPropertyFactored(props, "TransparentColor", "TransparencyFactor", ok); + float CalculatedOpacity = 1.0f; + if (ok) { + out_mat->AddProperty(&Transparent, 1, AI_MATKEY_COLOR_TRANSPARENT); + // as calculated by FBX SDK 2017: + CalculatedOpacity = 1.0f - ((Transparent.r + Transparent.g + Transparent.b) / 3.0f); + } + + // try to get the transparency factor + const float TransparencyFactor = PropertyGet(props, "TransparencyFactor", ok); + if (ok) { + out_mat->AddProperty(&TransparencyFactor, 1, AI_MATKEY_TRANSPARENCYFACTOR); + } + + // use of TransparencyFactor is inconsistent. + // Maya always stores it as 1.0, + // so we can't use it to set AI_MATKEY_OPACITY. + // Blender is more sensible and stores it as the alpha value. + // However both the FBX SDK and Blender always write an additional + // legacy "Opacity" field, so we can try to use that. + // + // If we can't find it, + // we can fall back to the value which the FBX SDK calculates + // from transparency colour (RGB) and factor (F) as + // 1.0 - F*((R+G+B)/3). + // + // There's no consistent way to interpret this opacity value, + // so it's up to clients to do the correct thing. + const float Opacity = PropertyGet(props, "Opacity", ok); + if (ok) { + out_mat->AddProperty(&Opacity, 1, AI_MATKEY_OPACITY); + } + else if (CalculatedOpacity != 1.0) { + out_mat->AddProperty(&CalculatedOpacity, 1, AI_MATKEY_OPACITY); + } + + // reflection color and factor are stored separately + const aiColor3D& Reflection = GetColorProperty(props, "ReflectionColor", ok, true); + if (ok) { + out_mat->AddProperty(&Reflection, 1, AI_MATKEY_COLOR_REFLECTIVE); + } + + float ReflectionFactor = PropertyGet(props, "ReflectionFactor", ok, true); + if (ok) { + out_mat->AddProperty(&ReflectionFactor, 1, AI_MATKEY_REFLECTIVITY); + } + + const float BumpFactor = PropertyGet(props, "BumpFactor", ok); + if (ok) { + out_mat->AddProperty(&BumpFactor, 1, AI_MATKEY_BUMPSCALING); + } + + const float DispFactor = PropertyGet(props, "DisplacementFactor", ok); + if (ok) { + out_mat->AddProperty(&DispFactor, 1, "$mat.displacementscaling", 0, 0); + } +} + + +void FBXConverter::SetShadingPropertiesRaw(aiMaterial* out_mat, const PropertyTable& props, const TextureMap& textures, const MeshGeometry* const mesh) +{ + // Add all the unparsed properties with a "$raw." prefix + + const std::string prefix = "$raw."; + + for (const DirectPropertyMap::value_type& prop : props.GetUnparsedProperties()) { + + std::string name = prefix + prop.first; + + if (const TypedProperty* interpreted = prop.second->As >()) + { + out_mat->AddProperty(&interpreted->Value(), 1, name.c_str(), 0, 0); + } + else if (const TypedProperty* interpreted = prop.second->As >()) + { + out_mat->AddProperty(&interpreted->Value(), 1, name.c_str(), 0, 0); + } + else if (const TypedProperty* interpreted = prop.second->As >()) + { + out_mat->AddProperty(&interpreted->Value(), 1, name.c_str(), 0, 0); + } + else if (const TypedProperty* interpreted = prop.second->As >()) + { + out_mat->AddProperty(&interpreted->Value(), 1, name.c_str(), 0, 0); + } + else if (const TypedProperty* interpreted = prop.second->As >()) + { + out_mat->AddProperty(&interpreted->Value(), 1, name.c_str(), 0, 0); + } + else if (const TypedProperty* interpreted = prop.second->As >()) + { + int value = interpreted->Value() ? 1 : 0; + out_mat->AddProperty(&value, 1, name.c_str(), 0, 0); + } + else if (const TypedProperty* interpreted = prop.second->As >()) + { + const aiString value = aiString(interpreted->Value()); + out_mat->AddProperty(&value, name.c_str(), 0, 0); + } + } + + // Add the textures' properties + + for (TextureMap::const_iterator it = textures.begin(); it != textures.end(); it++) { + + std::string name = prefix + it->first; + + const Texture* const tex = (*it).second; + if (tex != nullptr) + { + aiString path; + path.Set(tex->RelativeFilename()); + + const Video* media = tex->Media(); + if (media != nullptr && media->ContentLength() > 0) { + unsigned int index; + + VideoMap::const_iterator it = textures_converted.find(media); + if (it != textures_converted.end()) { + index = (*it).second; + } + else { + index = ConvertVideo(*media); + textures_converted[media] = index; + } + + // setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture) + path.data[0] = '*'; + path.length = 1 + ASSIMP_itoa10(path.data + 1, MAXLEN - 1, index); + } + + out_mat->AddProperty(&path, (name + "|file").c_str(), aiTextureType_UNKNOWN, 0); + + aiUVTransform uvTrafo; + // XXX handle all kinds of UV transformations + uvTrafo.mScaling = tex->UVScaling(); + uvTrafo.mTranslation = tex->UVTranslation(); + out_mat->AddProperty(&uvTrafo, 1, (name + "|uvtrafo").c_str(), aiTextureType_UNKNOWN, 0); + + int uvIndex = 0; + + bool uvFound = false; + const std::string& uvSet = PropertyGet(tex->Props(), "UVSet", uvFound); + if (uvFound) { + // "default" is the name which usually appears in the FbxFileTexture template + if (uvSet != "default" && uvSet.length()) { + // this is a bit awkward - we need to find a mesh that uses this + // material and scan its UV channels for the given UV name because + // assimp references UV channels by index, not by name. + + // XXX: the case that UV channels may appear in different orders + // in meshes is unhandled. A possible solution would be to sort + // the UV channels alphabetically, but this would have the side + // effect that the primary (first) UV channel would sometimes + // be moved, causing trouble when users read only the first + // UV channel and ignore UV channel assignments altogether. + + std::vector::iterator materialIt = std::find(materials.begin(), materials.end(), out_mat); + const unsigned int matIndex = static_cast(std::distance(materials.begin(), materialIt)); + + uvIndex = -1; + if (!mesh) + { + for (const MeshMap::value_type& v : meshes_converted) { + const MeshGeometry* const meshGeom = dynamic_cast(v.first); + if (!meshGeom) { + continue; + } + + const MatIndexArray& mats = meshGeom->GetMaterialIndices(); + if (std::find(mats.begin(), mats.end(), matIndex) == mats.end()) { + continue; + } + + int index = -1; + for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) { + if (meshGeom->GetTextureCoords(i).empty()) { + break; + } + const std::string& name = meshGeom->GetTextureCoordChannelName(i); + if (name == uvSet) { + index = static_cast(i); + break; + } + } + if (index == -1) { + FBXImporter::LogWarn("did not find UV channel named " + uvSet + " in a mesh using this material"); + continue; + } + + if (uvIndex == -1) { + uvIndex = index; + } + else { + FBXImporter::LogWarn("the UV channel named " + uvSet + " appears at different positions in meshes, results will be wrong"); + } + } + } + else + { + int index = -1; + for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) { + if (mesh->GetTextureCoords(i).empty()) { + break; + } + const std::string& name = mesh->GetTextureCoordChannelName(i); + if (name == uvSet) { + index = static_cast(i); + break; + } + } + if (index == -1) { + FBXImporter::LogWarn("did not find UV channel named " + uvSet + " in a mesh using this material"); + } + + if (uvIndex == -1) { + uvIndex = index; + } + } + + if (uvIndex == -1) { + FBXImporter::LogWarn("failed to resolve UV channel " + uvSet + ", using first UV channel"); + uvIndex = 0; + } + } + } + + out_mat->AddProperty(&uvIndex, 1, (name + "|uvwsrc").c_str(), aiTextureType_UNKNOWN, 0); + } + } + } + + + double FBXConverter::FrameRateToDouble(FileGlobalSettings::FrameRate fp, double customFPSVal) { + switch (fp) { + case FileGlobalSettings::FrameRate_DEFAULT: + return 1.0; + + case FileGlobalSettings::FrameRate_120: + return 120.0; + + case FileGlobalSettings::FrameRate_100: + return 100.0; + + case FileGlobalSettings::FrameRate_60: + return 60.0; + + case FileGlobalSettings::FrameRate_50: + return 50.0; + + case FileGlobalSettings::FrameRate_48: + return 48.0; + + case FileGlobalSettings::FrameRate_30: + case FileGlobalSettings::FrameRate_30_DROP: + return 30.0; + + case FileGlobalSettings::FrameRate_NTSC_DROP_FRAME: + case FileGlobalSettings::FrameRate_NTSC_FULL_FRAME: + return 29.9700262; + + case FileGlobalSettings::FrameRate_PAL: + return 25.0; + + case FileGlobalSettings::FrameRate_CINEMA: + return 24.0; + + case FileGlobalSettings::FrameRate_1000: + return 1000.0; + + case FileGlobalSettings::FrameRate_CINEMA_ND: + return 23.976; + + case FileGlobalSettings::FrameRate_CUSTOM: + return customFPSVal; + + case FileGlobalSettings::FrameRate_MAX: // this is to silence compiler warnings + break; + } + + ai_assert(false); + + return -1.0f; + } + + + void FBXConverter::ConvertAnimations() + { + // first of all determine framerate + const FileGlobalSettings::FrameRate fps = doc.GlobalSettings().TimeMode(); + const float custom = doc.GlobalSettings().CustomFrameRate(); + anim_fps = FrameRateToDouble(fps, custom); + + const std::vector& animations = doc.AnimationStacks(); + for (const AnimationStack* stack : animations) { + ConvertAnimationStack(*stack); + } + } + + std::string FBXConverter::FixNodeName(const std::string& name) { + // strip Model:: prefix, avoiding ambiguities (i.e. don't strip if + // this causes ambiguities, well possible between empty identifiers, + // such as "Model::" and ""). Make sure the behaviour is consistent + // across multiple calls to FixNodeName(). + if (name.substr(0, 7) == "Model::") { + std::string temp = name.substr(7); + return temp; + } + + return name; + } + + std::string FBXConverter::FixAnimMeshName(const std::string& name) { + if (name.length()) { + size_t indexOf = name.find_first_of("::"); + if (indexOf != std::string::npos && indexOf < name.size() - 2) { + return name.substr(indexOf + 2); + } + } + return name.length() ? name : "AnimMesh"; + } + + void FBXConverter::ConvertAnimationStack(const AnimationStack& st) + { + const AnimationLayerList& layers = st.Layers(); + if (layers.empty()) { + return; + } + + aiAnimation* const anim = new aiAnimation(); + animations.push_back(anim); + + // strip AnimationStack:: prefix + std::string name = st.Name(); + if (name.substr(0, 16) == "AnimationStack::") { + name = name.substr(16); + } + else if (name.substr(0, 11) == "AnimStack::") { + name = name.substr(11); + } + + anim->mName.Set(name); + + // need to find all nodes for which we need to generate node animations - + // it may happen that we need to merge multiple layers, though. + NodeMap node_map; + + // reverse mapping from curves to layers, much faster than querying + // the FBX DOM for it. + LayerMap layer_map; + + const char* prop_whitelist[] = { + "Lcl Scaling", + "Lcl Rotation", + "Lcl Translation", + "DeformPercent" + }; + + std::map morphAnimDatas; + + for (const AnimationLayer* layer : layers) { + ai_assert(layer); + const AnimationCurveNodeList& nodes = layer->Nodes(prop_whitelist, 4); + for (const AnimationCurveNode* node : nodes) { + ai_assert(node); + const Model* const model = dynamic_cast(node->Target()); + if (model) { + const std::string& name = FixNodeName(model->Name()); + node_map[name].push_back(node); + layer_map[node] = layer; + continue; + } + const BlendShapeChannel* const bsc = dynamic_cast(node->Target()); + if (bsc) { + ProcessMorphAnimDatas(&morphAnimDatas, bsc, node); + } + } + } + + // generate node animations + std::vector node_anims; + + double min_time = 1e10; + double max_time = -1e10; + + int64_t start_time = st.LocalStart(); + int64_t stop_time = st.LocalStop(); + bool has_local_startstop = start_time != 0 || stop_time != 0; + if (!has_local_startstop) { + // no time range given, so accept every keyframe and use the actual min/max time + // the numbers are INT64_MIN/MAX, the 20000 is for safety because GenerateNodeAnimations uses an epsilon of 10000 + start_time = -9223372036854775807ll + 20000; + stop_time = 9223372036854775807ll - 20000; + } + + try { + for (const NodeMap::value_type& kv : node_map) { + GenerateNodeAnimations(node_anims, + kv.first, + kv.second, + layer_map, + start_time, stop_time, + max_time, + min_time); + } + } + catch (std::exception&) { + std::for_each(node_anims.begin(), node_anims.end(), Util::delete_fun()); + throw; + } + + if (node_anims.size() || morphAnimDatas.size()) { + if (node_anims.size()) { + anim->mChannels = new aiNodeAnim*[node_anims.size()](); + anim->mNumChannels = static_cast(node_anims.size()); + std::swap_ranges(node_anims.begin(), node_anims.end(), anim->mChannels); + } + if (morphAnimDatas.size()) { + unsigned int numMorphMeshChannels = static_cast(morphAnimDatas.size()); + anim->mMorphMeshChannels = new aiMeshMorphAnim*[numMorphMeshChannels]; + anim->mNumMorphMeshChannels = numMorphMeshChannels; + unsigned int i = 0; + for (auto morphAnimIt : morphAnimDatas) { + morphAnimData* animData = morphAnimIt.second; + unsigned int numKeys = static_cast(animData->size()); + aiMeshMorphAnim* meshMorphAnim = new aiMeshMorphAnim(); + meshMorphAnim->mName.Set(morphAnimIt.first); + meshMorphAnim->mNumKeys = numKeys; + meshMorphAnim->mKeys = new aiMeshMorphKey[numKeys]; + unsigned int j = 0; + for (auto animIt : *animData) { + morphKeyData* keyData = animIt.second; + unsigned int numValuesAndWeights = static_cast(keyData->values.size()); + meshMorphAnim->mKeys[j].mNumValuesAndWeights = numValuesAndWeights; + meshMorphAnim->mKeys[j].mValues = new unsigned int[numValuesAndWeights]; + meshMorphAnim->mKeys[j].mWeights = new double[numValuesAndWeights]; + meshMorphAnim->mKeys[j].mTime = CONVERT_FBX_TIME(animIt.first) * anim_fps; + for (unsigned int k = 0; k < numValuesAndWeights; k++) { + meshMorphAnim->mKeys[j].mValues[k] = keyData->values.at(k); + meshMorphAnim->mKeys[j].mWeights[k] = keyData->weights.at(k); + } + j++; + } + anim->mMorphMeshChannels[i++] = meshMorphAnim; + } + } + } + else { + // empty animations would fail validation, so drop them + delete anim; + animations.pop_back(); + FBXImporter::LogInfo("ignoring empty AnimationStack (using IK?): " + name); + return; + } + + double start_time_fps = has_local_startstop ? (CONVERT_FBX_TIME(start_time) * anim_fps) : min_time; + double stop_time_fps = has_local_startstop ? (CONVERT_FBX_TIME(stop_time) * anim_fps) : max_time; + + // adjust relative timing for animation + for (unsigned int c = 0; c < anim->mNumChannels; c++) { + aiNodeAnim* channel = anim->mChannels[c]; + for (uint32_t i = 0; i < channel->mNumPositionKeys; i++) { + channel->mPositionKeys[i].mTime -= start_time_fps; + } + for (uint32_t i = 0; i < channel->mNumRotationKeys; i++) { + channel->mRotationKeys[i].mTime -= start_time_fps; + } + for (uint32_t i = 0; i < channel->mNumScalingKeys; i++) { + channel->mScalingKeys[i].mTime -= start_time_fps; + } + } + for (unsigned int c = 0; c < anim->mNumMorphMeshChannels; c++) { + aiMeshMorphAnim* channel = anim->mMorphMeshChannels[c]; + for (uint32_t i = 0; i < channel->mNumKeys; i++) { + channel->mKeys[i].mTime -= start_time_fps; + } + } + + // for some mysterious reason, mDuration is simply the maximum key -- the + // validator always assumes animations to start at zero. + anim->mDuration = stop_time_fps - start_time_fps; + anim->mTicksPerSecond = anim_fps; + } + + // ------------------------------------------------------------------------------------------------ + void FBXConverter::ProcessMorphAnimDatas(std::map* morphAnimDatas, const BlendShapeChannel* bsc, const AnimationCurveNode* node) { + std::vector bscConnections = doc.GetConnectionsBySourceSequenced(bsc->ID(), "Deformer"); + for (const Connection* bscConnection : bscConnections) { + auto bs = dynamic_cast(bscConnection->DestinationObject()); + if (bs) { + auto channelIt = std::find(bs->BlendShapeChannels().begin(), bs->BlendShapeChannels().end(), bsc); + if (channelIt != bs->BlendShapeChannels().end()) { + auto channelIndex = static_cast(std::distance(bs->BlendShapeChannels().begin(), channelIt)); + std::vector bsConnections = doc.GetConnectionsBySourceSequenced(bs->ID(), "Geometry"); + for (const Connection* bsConnection : bsConnections) { + auto geo = dynamic_cast(bsConnection->DestinationObject()); + if (geo) { + std::vector geoConnections = doc.GetConnectionsBySourceSequenced(geo->ID(), "Model"); + for (const Connection* geoConnection : geoConnections) { + auto model = dynamic_cast(geoConnection->DestinationObject()); + if (model) { + auto geoIt = std::find(model->GetGeometry().begin(), model->GetGeometry().end(), geo); + auto geoIndex = static_cast(std::distance(model->GetGeometry().begin(), geoIt)); + auto name = aiString(FixNodeName(model->Name() + "*")); + name.length = 1 + ASSIMP_itoa10(name.data + name.length, MAXLEN - 1, geoIndex); + morphAnimData* animData; + auto animIt = morphAnimDatas->find(name.C_Str()); + if (animIt == morphAnimDatas->end()) { + animData = new morphAnimData(); + morphAnimDatas->insert(std::make_pair(name.C_Str(), animData)); + } + else { + animData = animIt->second; + } + for (std::pair curvesIt : node->Curves()) { + if (curvesIt.first == "d|DeformPercent") { + const AnimationCurve* animationCurve = curvesIt.second; + const KeyTimeList& keys = animationCurve->GetKeys(); + const KeyValueList& values = animationCurve->GetValues(); + unsigned int k = 0; + for (auto key : keys) { + morphKeyData* keyData; + auto keyIt = animData->find(key); + if (keyIt == animData->end()) { + keyData = new morphKeyData(); + animData->insert(std::make_pair(key, keyData)); + } + else { + keyData = keyIt->second; + } + keyData->values.push_back(channelIndex); + keyData->weights.push_back(values.at(k) / 100.0f); + k++; + } + } + } + } + } + } + } + } + } + } + } + + // ------------------------------------------------------------------------------------------------ +#ifdef ASSIMP_BUILD_DEBUG + // ------------------------------------------------------------------------------------------------ + // sanity check whether the input is ok + static void validateAnimCurveNodes(const std::vector& curves, + bool strictMode) { + const Object* target(NULL); + for (const AnimationCurveNode* node : curves) { + if (!target) { + target = node->Target(); + } + if (node->Target() != target) { + FBXImporter::LogWarn("Node target is nullptr type."); + } + if (strictMode) { + ai_assert(node->Target() == target); + } + } + } +#endif // ASSIMP_BUILD_DEBUG + + // ------------------------------------------------------------------------------------------------ + void FBXConverter::GenerateNodeAnimations(std::vector& node_anims, + const std::string& fixed_name, + const std::vector& curves, + const LayerMap& layer_map, + int64_t start, int64_t stop, + double& max_time, + double& min_time) + { + + NodeMap node_property_map; + ai_assert(curves.size()); + +#ifdef ASSIMP_BUILD_DEBUG + validateAnimCurveNodes(curves, doc.Settings().strictMode); +#endif + const AnimationCurveNode* curve_node = NULL; + for (const AnimationCurveNode* node : curves) { + ai_assert(node); + + if (node->TargetProperty().empty()) { + FBXImporter::LogWarn("target property for animation curve not set: " + node->Name()); + continue; + } + + curve_node = node; + if (node->Curves().empty()) { + FBXImporter::LogWarn("no animation curves assigned to AnimationCurveNode: " + node->Name()); + continue; + } + + node_property_map[node->TargetProperty()].push_back(node); + } + + ai_assert(curve_node); + ai_assert(curve_node->TargetAsModel()); + + const Model& target = *curve_node->TargetAsModel(); + + // check for all possible transformation components + NodeMap::const_iterator chain[TransformationComp_MAXIMUM]; + + bool has_any = false; + bool has_complex = false; + + for (size_t i = 0; i < TransformationComp_MAXIMUM; ++i) { + const TransformationComp comp = static_cast(i); + + // inverse pivots don't exist in the input, we just generate them + if (comp == TransformationComp_RotationPivotInverse || comp == TransformationComp_ScalingPivotInverse) { + chain[i] = node_property_map.end(); + continue; + } + + chain[i] = node_property_map.find(NameTransformationCompProperty(comp)); + if (chain[i] != node_property_map.end()) { + + // check if this curves contains redundant information by looking + // up the corresponding node's transformation chain. + if (doc.Settings().optimizeEmptyAnimationCurves && + IsRedundantAnimationData(target, comp, (*chain[i]).second)) { + + FBXImporter::LogDebug("dropping redundant animation channel for node " + target.Name()); + continue; + } + + has_any = true; + + if (comp != TransformationComp_Rotation && comp != TransformationComp_Scaling && comp != TransformationComp_Translation) + { + has_complex = true; + } + } + } + + if (!has_any) { + FBXImporter::LogWarn("ignoring node animation, did not find any transformation key frames"); + return; + } + + // this needs to play nicely with GenerateTransformationNodeChain() which will + // be invoked _later_ (animations come first). If this node has only rotation, + // scaling and translation _and_ there are no animated other components either, + // we can use a single node and also a single node animation channel. + if (!has_complex && !NeedsComplexTransformationChain(target)) { + + aiNodeAnim* const nd = GenerateSimpleNodeAnim(fixed_name, target, chain, + node_property_map.end(), + layer_map, + start, stop, + max_time, + min_time, + true // input is TRS order, assimp is SRT + ); + + ai_assert(nd); + if (nd->mNumPositionKeys == 0 && nd->mNumRotationKeys == 0 && nd->mNumScalingKeys == 0) { + delete nd; + } + else { + node_anims.push_back(nd); + } + return; + } + + // otherwise, things get gruesome and we need separate animation channels + // for each part of the transformation chain. Remember which channels + // we generated and pass this information to the node conversion + // code to avoid nodes that have identity transform, but non-identity + // animations, being dropped. + unsigned int flags = 0, bit = 0x1; + for (size_t i = 0; i < TransformationComp_MAXIMUM; ++i, bit <<= 1) { + const TransformationComp comp = static_cast(i); + + if (chain[i] != node_property_map.end()) { + flags |= bit; + + ai_assert(comp != TransformationComp_RotationPivotInverse); + ai_assert(comp != TransformationComp_ScalingPivotInverse); + + const std::string& chain_name = NameTransformationChainNode(fixed_name, comp); + + aiNodeAnim* na = nullptr; + switch (comp) + { + case TransformationComp_Rotation: + case TransformationComp_PreRotation: + case TransformationComp_PostRotation: + case TransformationComp_GeometricRotation: + na = GenerateRotationNodeAnim(chain_name, + target, + (*chain[i]).second, + layer_map, + start, stop, + max_time, + min_time); + + break; + + case TransformationComp_RotationOffset: + case TransformationComp_RotationPivot: + case TransformationComp_ScalingOffset: + case TransformationComp_ScalingPivot: + case TransformationComp_Translation: + case TransformationComp_GeometricTranslation: + na = GenerateTranslationNodeAnim(chain_name, + target, + (*chain[i]).second, + layer_map, + start, stop, + max_time, + min_time); + + // pivoting requires us to generate an implicit inverse channel to undo the pivot translation + if (comp == TransformationComp_RotationPivot) { + const std::string& invName = NameTransformationChainNode(fixed_name, + TransformationComp_RotationPivotInverse); + + aiNodeAnim* const inv = GenerateTranslationNodeAnim(invName, + target, + (*chain[i]).second, + layer_map, + start, stop, + max_time, + min_time, + true); + + ai_assert(inv); + if (inv->mNumPositionKeys == 0 && inv->mNumRotationKeys == 0 && inv->mNumScalingKeys == 0) { + delete inv; + } + else { + node_anims.push_back(inv); + } + + ai_assert(TransformationComp_RotationPivotInverse > i); + flags |= bit << (TransformationComp_RotationPivotInverse - i); + } + else if (comp == TransformationComp_ScalingPivot) { + const std::string& invName = NameTransformationChainNode(fixed_name, + TransformationComp_ScalingPivotInverse); + + aiNodeAnim* const inv = GenerateTranslationNodeAnim(invName, + target, + (*chain[i]).second, + layer_map, + start, stop, + max_time, + min_time, + true); + + ai_assert(inv); + if (inv->mNumPositionKeys == 0 && inv->mNumRotationKeys == 0 && inv->mNumScalingKeys == 0) { + delete inv; + } + else { + node_anims.push_back(inv); + } + + ai_assert(TransformationComp_RotationPivotInverse > i); + flags |= bit << (TransformationComp_RotationPivotInverse - i); + } + + break; + + case TransformationComp_Scaling: + case TransformationComp_GeometricScaling: + na = GenerateScalingNodeAnim(chain_name, + target, + (*chain[i]).second, + layer_map, + start, stop, + max_time, + min_time); + + break; + + default: + ai_assert(false); + } + + ai_assert(na); + if (na->mNumPositionKeys == 0 && na->mNumRotationKeys == 0 && na->mNumScalingKeys == 0) { + delete na; + } + else { + node_anims.push_back(na); + } + continue; + } + } + + node_anim_chain_bits[fixed_name] = flags; + } + + + bool FBXConverter::IsRedundantAnimationData(const Model& target, + TransformationComp comp, + const std::vector& curves) { + ai_assert(curves.size()); + + // look for animation nodes with + // * sub channels for all relevant components set + // * one key/value pair per component + // * combined values match up the corresponding value in the bind pose node transformation + // only such nodes are 'redundant' for this function. + + if (curves.size() > 1) { + return false; + } + + const AnimationCurveNode& nd = *curves.front(); + const AnimationCurveMap& sub_curves = nd.Curves(); + + const AnimationCurveMap::const_iterator dx = sub_curves.find("d|X"); + const AnimationCurveMap::const_iterator dy = sub_curves.find("d|Y"); + const AnimationCurveMap::const_iterator dz = sub_curves.find("d|Z"); + + if (dx == sub_curves.end() || dy == sub_curves.end() || dz == sub_curves.end()) { + return false; + } + + const KeyValueList& vx = (*dx).second->GetValues(); + const KeyValueList& vy = (*dy).second->GetValues(); + const KeyValueList& vz = (*dz).second->GetValues(); + + if (vx.size() != 1 || vy.size() != 1 || vz.size() != 1) { + return false; + } + + const aiVector3D dyn_val = aiVector3D(vx[0], vy[0], vz[0]); + const aiVector3D& static_val = PropertyGet(target.Props(), + NameTransformationCompProperty(comp), + TransformationCompDefaultValue(comp) + ); + + const float epsilon = Math::getEpsilon(); + return (dyn_val - static_val).SquareLength() < epsilon; + } + + + aiNodeAnim* FBXConverter::GenerateRotationNodeAnim(const std::string& name, + const Model& target, + const std::vector& curves, + const LayerMap& layer_map, + int64_t start, int64_t stop, + double& max_time, + double& min_time) + { + std::unique_ptr na(new aiNodeAnim()); + na->mNodeName.Set(name); + + ConvertRotationKeys(na.get(), curves, layer_map, start, stop, max_time, min_time, target.RotationOrder()); + + // dummy scaling key + na->mScalingKeys = new aiVectorKey[1]; + na->mNumScalingKeys = 1; + + na->mScalingKeys[0].mTime = 0.; + na->mScalingKeys[0].mValue = aiVector3D(1.0f, 1.0f, 1.0f); + + // dummy position key + na->mPositionKeys = new aiVectorKey[1]; + na->mNumPositionKeys = 1; + + na->mPositionKeys[0].mTime = 0.; + na->mPositionKeys[0].mValue = aiVector3D(); + + return na.release(); + } + + aiNodeAnim* FBXConverter::GenerateScalingNodeAnim(const std::string& name, + const Model& /*target*/, + const std::vector& curves, + const LayerMap& layer_map, + int64_t start, int64_t stop, + double& max_time, + double& min_time) + { + std::unique_ptr na(new aiNodeAnim()); + na->mNodeName.Set(name); + + ConvertScaleKeys(na.get(), curves, layer_map, start, stop, max_time, min_time); + + // dummy rotation key + na->mRotationKeys = new aiQuatKey[1]; + na->mNumRotationKeys = 1; + + na->mRotationKeys[0].mTime = 0.; + na->mRotationKeys[0].mValue = aiQuaternion(); + + // dummy position key + na->mPositionKeys = new aiVectorKey[1]; + na->mNumPositionKeys = 1; + + na->mPositionKeys[0].mTime = 0.; + na->mPositionKeys[0].mValue = aiVector3D(); + + return na.release(); + } + + aiNodeAnim* FBXConverter::GenerateTranslationNodeAnim(const std::string& name, + const Model& /*target*/, + const std::vector& curves, + const LayerMap& layer_map, + int64_t start, int64_t stop, + double& max_time, + double& min_time, + bool inverse) { + std::unique_ptr na(new aiNodeAnim()); + na->mNodeName.Set(name); + + ConvertTranslationKeys(na.get(), curves, layer_map, start, stop, max_time, min_time); + + if (inverse) { + for (unsigned int i = 0; i < na->mNumPositionKeys; ++i) { + na->mPositionKeys[i].mValue *= -1.0f; + } + } + + // dummy scaling key + na->mScalingKeys = new aiVectorKey[1]; + na->mNumScalingKeys = 1; + + na->mScalingKeys[0].mTime = 0.; + na->mScalingKeys[0].mValue = aiVector3D(1.0f, 1.0f, 1.0f); + + // dummy rotation key + na->mRotationKeys = new aiQuatKey[1]; + na->mNumRotationKeys = 1; + + na->mRotationKeys[0].mTime = 0.; + na->mRotationKeys[0].mValue = aiQuaternion(); + + return na.release(); + } + + aiNodeAnim* FBXConverter::GenerateSimpleNodeAnim(const std::string& name, + const Model& target, + NodeMap::const_iterator chain[TransformationComp_MAXIMUM], + NodeMap::const_iterator iter_end, + const LayerMap& layer_map, + int64_t start, int64_t stop, + double& max_time, + double& min_time, + bool reverse_order) + + { + std::unique_ptr na(new aiNodeAnim()); + na->mNodeName.Set(name); + + const PropertyTable& props = target.Props(); + + // need to convert from TRS order to SRT? + if (reverse_order) { + + aiVector3D def_scale = PropertyGet(props, "Lcl Scaling", aiVector3D(1.f, 1.f, 1.f)); + aiVector3D def_translate = PropertyGet(props, "Lcl Translation", aiVector3D(0.f, 0.f, 0.f)); + aiVector3D def_rot = PropertyGet(props, "Lcl Rotation", aiVector3D(0.f, 0.f, 0.f)); + + KeyFrameListList scaling; + KeyFrameListList translation; + KeyFrameListList rotation; + + if (chain[TransformationComp_Scaling] != iter_end) { + scaling = GetKeyframeList((*chain[TransformationComp_Scaling]).second, start, stop); + } + + if (chain[TransformationComp_Translation] != iter_end) { + translation = GetKeyframeList((*chain[TransformationComp_Translation]).second, start, stop); + } + + if (chain[TransformationComp_Rotation] != iter_end) { + rotation = GetKeyframeList((*chain[TransformationComp_Rotation]).second, start, stop); + } + + KeyFrameListList joined; + joined.insert(joined.end(), scaling.begin(), scaling.end()); + joined.insert(joined.end(), translation.begin(), translation.end()); + joined.insert(joined.end(), rotation.begin(), rotation.end()); + + const KeyTimeList& times = GetKeyTimeList(joined); + + aiQuatKey* out_quat = new aiQuatKey[times.size()]; + aiVectorKey* out_scale = new aiVectorKey[times.size()]; + aiVectorKey* out_translation = new aiVectorKey[times.size()]; + + if (times.size()) + { + ConvertTransformOrder_TRStoSRT(out_quat, out_scale, out_translation, + scaling, + translation, + rotation, + times, + max_time, + min_time, + target.RotationOrder(), + def_scale, + def_translate, + def_rot); + } + + // XXX remove duplicates / redundant keys which this operation did + // likely produce if not all three channels were equally dense. + + na->mNumScalingKeys = static_cast(times.size()); + na->mNumRotationKeys = na->mNumScalingKeys; + na->mNumPositionKeys = na->mNumScalingKeys; + + na->mScalingKeys = out_scale; + na->mRotationKeys = out_quat; + na->mPositionKeys = out_translation; + } + else { + + // if a particular transformation is not given, grab it from + // the corresponding node to meet the semantics of aiNodeAnim, + // which requires all of rotation, scaling and translation + // to be set. + if (chain[TransformationComp_Scaling] != iter_end) { + ConvertScaleKeys(na.get(), (*chain[TransformationComp_Scaling]).second, + layer_map, + start, stop, + max_time, + min_time); + } + else { + na->mScalingKeys = new aiVectorKey[1]; + na->mNumScalingKeys = 1; + + na->mScalingKeys[0].mTime = 0.; + na->mScalingKeys[0].mValue = PropertyGet(props, "Lcl Scaling", + aiVector3D(1.f, 1.f, 1.f)); + } + + if (chain[TransformationComp_Rotation] != iter_end) { + ConvertRotationKeys(na.get(), (*chain[TransformationComp_Rotation]).second, + layer_map, + start, stop, + max_time, + min_time, + target.RotationOrder()); + } + else { + na->mRotationKeys = new aiQuatKey[1]; + na->mNumRotationKeys = 1; + + na->mRotationKeys[0].mTime = 0.; + na->mRotationKeys[0].mValue = EulerToQuaternion( + PropertyGet(props, "Lcl Rotation", aiVector3D(0.f, 0.f, 0.f)), + target.RotationOrder()); + } + + if (chain[TransformationComp_Translation] != iter_end) { + ConvertTranslationKeys(na.get(), (*chain[TransformationComp_Translation]).second, + layer_map, + start, stop, + max_time, + min_time); + } + else { + na->mPositionKeys = new aiVectorKey[1]; + na->mNumPositionKeys = 1; + + na->mPositionKeys[0].mTime = 0.; + na->mPositionKeys[0].mValue = PropertyGet(props, "Lcl Translation", + aiVector3D(0.f, 0.f, 0.f)); + } + + } + return na.release(); + } + + FBXConverter::KeyFrameListList FBXConverter::GetKeyframeList(const std::vector& nodes, int64_t start, int64_t stop) + { + KeyFrameListList inputs; + inputs.reserve(nodes.size() * 3); + + //give some breathing room for rounding errors + int64_t adj_start = start - 10000; + int64_t adj_stop = stop + 10000; + + for (const AnimationCurveNode* node : nodes) { + ai_assert(node); + + const AnimationCurveMap& curves = node->Curves(); + for (const AnimationCurveMap::value_type& kv : curves) { + + unsigned int mapto; + if (kv.first == "d|X") { + mapto = 0; + } + else if (kv.first == "d|Y") { + mapto = 1; + } + else if (kv.first == "d|Z") { + mapto = 2; + } + else { + FBXImporter::LogWarn("ignoring scale animation curve, did not recognize target component"); + continue; + } + + const AnimationCurve* const curve = kv.second; + ai_assert(curve->GetKeys().size() == curve->GetValues().size() && curve->GetKeys().size()); + + //get values within the start/stop time window + std::shared_ptr Keys(new KeyTimeList()); + std::shared_ptr Values(new KeyValueList()); + const size_t count = curve->GetKeys().size(); + Keys->reserve(count); + Values->reserve(count); + for (size_t n = 0; n < count; n++) + { + int64_t k = curve->GetKeys().at(n); + if (k >= adj_start && k <= adj_stop) + { + Keys->push_back(k); + Values->push_back(curve->GetValues().at(n)); + } + } + + inputs.push_back(std::make_tuple(Keys, Values, mapto)); + } + } + return inputs; // pray for NRVO :-) + } + + + KeyTimeList FBXConverter::GetKeyTimeList(const KeyFrameListList& inputs) { + ai_assert(!inputs.empty()); + + // reserve some space upfront - it is likely that the key-frame lists + // have matching time values, so max(of all key-frame lists) should + // be a good estimate. + KeyTimeList keys; + + size_t estimate = 0; + for (const KeyFrameList& kfl : inputs) { + estimate = std::max(estimate, std::get<0>(kfl)->size()); + } + + keys.reserve(estimate); + + std::vector next_pos; + next_pos.resize(inputs.size(), 0); + + const size_t count = inputs.size(); + while (true) { + + int64_t min_tick = std::numeric_limits::max(); + for (size_t i = 0; i < count; ++i) { + const KeyFrameList& kfl = inputs[i]; + + if (std::get<0>(kfl)->size() > next_pos[i] && std::get<0>(kfl)->at(next_pos[i]) < min_tick) { + min_tick = std::get<0>(kfl)->at(next_pos[i]); + } + } + + if (min_tick == std::numeric_limits::max()) { + break; + } + keys.push_back(min_tick); + + for (size_t i = 0; i < count; ++i) { + const KeyFrameList& kfl = inputs[i]; + + + while (std::get<0>(kfl)->size() > next_pos[i] && std::get<0>(kfl)->at(next_pos[i]) == min_tick) { + ++next_pos[i]; + } + } + } + + return keys; + } + + void FBXConverter::InterpolateKeys(aiVectorKey* valOut, const KeyTimeList& keys, const KeyFrameListList& inputs, + const aiVector3D& def_value, + double& max_time, + double& min_time) { + ai_assert(!keys.empty()); + ai_assert(nullptr != valOut); + + std::vector next_pos; + const size_t count(inputs.size()); + + next_pos.resize(inputs.size(), 0); + + for (KeyTimeList::value_type time : keys) { + ai_real result[3] = { def_value.x, def_value.y, def_value.z }; + + for (size_t i = 0; i < count; ++i) { + const KeyFrameList& kfl = inputs[i]; + + const size_t ksize = std::get<0>(kfl)->size(); + if (ksize == 0) { + continue; + } + if (ksize > next_pos[i] && std::get<0>(kfl)->at(next_pos[i]) == time) { + ++next_pos[i]; + } + + const size_t id0 = next_pos[i] > 0 ? next_pos[i] - 1 : 0; + const size_t id1 = next_pos[i] == ksize ? ksize - 1 : next_pos[i]; + + // use lerp for interpolation + const KeyValueList::value_type valueA = std::get<1>(kfl)->at(id0); + const KeyValueList::value_type valueB = std::get<1>(kfl)->at(id1); + + const KeyTimeList::value_type timeA = std::get<0>(kfl)->at(id0); + const KeyTimeList::value_type timeB = std::get<0>(kfl)->at(id1); + + const ai_real factor = timeB == timeA ? ai_real(0.) : static_cast((time - timeA)) / (timeB - timeA); + const ai_real interpValue = static_cast(valueA + (valueB - valueA) * factor); + + result[std::get<2>(kfl)] = interpValue; + } + + // magic value to convert fbx times to seconds + valOut->mTime = CONVERT_FBX_TIME(time) * anim_fps; + + min_time = std::min(min_time, valOut->mTime); + max_time = std::max(max_time, valOut->mTime); + + valOut->mValue.x = result[0]; + valOut->mValue.y = result[1]; + valOut->mValue.z = result[2]; + + ++valOut; + } + } + + void FBXConverter::InterpolateKeys(aiQuatKey* valOut, const KeyTimeList& keys, const KeyFrameListList& inputs, + const aiVector3D& def_value, + double& maxTime, + double& minTime, + Model::RotOrder order) + { + ai_assert(!keys.empty()); + ai_assert(nullptr != valOut); + + std::unique_ptr temp(new aiVectorKey[keys.size()]); + InterpolateKeys(temp.get(), keys, inputs, def_value, maxTime, minTime); + + aiMatrix4x4 m; + + aiQuaternion lastq; + + for (size_t i = 0, c = keys.size(); i < c; ++i) { + + valOut[i].mTime = temp[i].mTime; + + GetRotationMatrix(order, temp[i].mValue, m); + aiQuaternion quat = aiQuaternion(aiMatrix3x3(m)); + + // take shortest path by checking the inner product + // http://www.3dkingdoms.com/weekly/weekly.php?a=36 + if (quat.x * lastq.x + quat.y * lastq.y + quat.z * lastq.z + quat.w * lastq.w < 0) + { + quat.x = -quat.x; + quat.y = -quat.y; + quat.z = -quat.z; + quat.w = -quat.w; + } + lastq = quat; + + valOut[i].mValue = quat; + } + } + + void FBXConverter::ConvertTransformOrder_TRStoSRT(aiQuatKey* out_quat, aiVectorKey* out_scale, + aiVectorKey* out_translation, + const KeyFrameListList& scaling, + const KeyFrameListList& translation, + const KeyFrameListList& rotation, + const KeyTimeList& times, + double& maxTime, + double& minTime, + Model::RotOrder order, + const aiVector3D& def_scale, + const aiVector3D& def_translate, + const aiVector3D& def_rotation) + { + if (rotation.size()) { + InterpolateKeys(out_quat, times, rotation, def_rotation, maxTime, minTime, order); + } + else { + for (size_t i = 0; i < times.size(); ++i) { + out_quat[i].mTime = CONVERT_FBX_TIME(times[i]) * anim_fps; + out_quat[i].mValue = EulerToQuaternion(def_rotation, order); + } + } + + if (scaling.size()) { + InterpolateKeys(out_scale, times, scaling, def_scale, maxTime, minTime); + } + else { + for (size_t i = 0; i < times.size(); ++i) { + out_scale[i].mTime = CONVERT_FBX_TIME(times[i]) * anim_fps; + out_scale[i].mValue = def_scale; + } + } + + if (translation.size()) { + InterpolateKeys(out_translation, times, translation, def_translate, maxTime, minTime); + } + else { + for (size_t i = 0; i < times.size(); ++i) { + out_translation[i].mTime = CONVERT_FBX_TIME(times[i]) * anim_fps; + out_translation[i].mValue = def_translate; + } + } + + const size_t count = times.size(); + for (size_t i = 0; i < count; ++i) { + aiQuaternion& r = out_quat[i].mValue; + aiVector3D& s = out_scale[i].mValue; + aiVector3D& t = out_translation[i].mValue; + + aiMatrix4x4 mat, temp; + aiMatrix4x4::Translation(t, mat); + mat *= aiMatrix4x4(r.GetMatrix()); + mat *= aiMatrix4x4::Scaling(s, temp); + + mat.Decompose(s, r, t); + } + } + + aiQuaternion FBXConverter::EulerToQuaternion(const aiVector3D& rot, Model::RotOrder order) + { + aiMatrix4x4 m; + GetRotationMatrix(order, rot, m); + + return aiQuaternion(aiMatrix3x3(m)); + } + + void FBXConverter::ConvertScaleKeys(aiNodeAnim* na, const std::vector& nodes, const LayerMap& /*layers*/, + int64_t start, int64_t stop, + double& maxTime, + double& minTime) + { + ai_assert(nodes.size()); + + // XXX for now, assume scale should be blended geometrically (i.e. two + // layers should be multiplied with each other). There is a FBX + // property in the layer to specify the behaviour, though. + + const KeyFrameListList& inputs = GetKeyframeList(nodes, start, stop); + const KeyTimeList& keys = GetKeyTimeList(inputs); + + na->mNumScalingKeys = static_cast(keys.size()); + na->mScalingKeys = new aiVectorKey[keys.size()]; + if (keys.size() > 0) { + InterpolateKeys(na->mScalingKeys, keys, inputs, aiVector3D(1.0f, 1.0f, 1.0f), maxTime, minTime); + } + } + + void FBXConverter::ConvertTranslationKeys(aiNodeAnim* na, const std::vector& nodes, + const LayerMap& /*layers*/, + int64_t start, int64_t stop, + double& maxTime, + double& minTime) + { + ai_assert(nodes.size()); + + // XXX see notes in ConvertScaleKeys() + const KeyFrameListList& inputs = GetKeyframeList(nodes, start, stop); + const KeyTimeList& keys = GetKeyTimeList(inputs); + + na->mNumPositionKeys = static_cast(keys.size()); + na->mPositionKeys = new aiVectorKey[keys.size()]; + if (keys.size() > 0) + InterpolateKeys(na->mPositionKeys, keys, inputs, aiVector3D(0.0f, 0.0f, 0.0f), maxTime, minTime); + } + + void FBXConverter::ConvertRotationKeys(aiNodeAnim* na, const std::vector& nodes, + const LayerMap& /*layers*/, + int64_t start, int64_t stop, + double& maxTime, + double& minTime, + Model::RotOrder order) + { + ai_assert(nodes.size()); + + // XXX see notes in ConvertScaleKeys() + const std::vector< KeyFrameList >& inputs = GetKeyframeList(nodes, start, stop); + const KeyTimeList& keys = GetKeyTimeList(inputs); + + na->mNumRotationKeys = static_cast(keys.size()); + na->mRotationKeys = new aiQuatKey[keys.size()]; + if (!keys.empty()) { + InterpolateKeys(na->mRotationKeys, keys, inputs, aiVector3D(0.0f, 0.0f, 0.0f), maxTime, minTime, order); + } + } + + void FBXConverter::ConvertGlobalSettings() { + if (nullptr == out) { + return; + } + + out->mMetaData = aiMetadata::Alloc(15); + out->mMetaData->Set(0, "UpAxis", doc.GlobalSettings().UpAxis()); + out->mMetaData->Set(1, "UpAxisSign", doc.GlobalSettings().UpAxisSign()); + out->mMetaData->Set(2, "FrontAxis", doc.GlobalSettings().FrontAxis()); + out->mMetaData->Set(3, "FrontAxisSign", doc.GlobalSettings().FrontAxisSign()); + out->mMetaData->Set(4, "CoordAxis", doc.GlobalSettings().CoordAxis()); + out->mMetaData->Set(5, "CoordAxisSign", doc.GlobalSettings().CoordAxisSign()); + out->mMetaData->Set(6, "OriginalUpAxis", doc.GlobalSettings().OriginalUpAxis()); + out->mMetaData->Set(7, "OriginalUpAxisSign", doc.GlobalSettings().OriginalUpAxisSign()); + out->mMetaData->Set(8, "UnitScaleFactor", (double)doc.GlobalSettings().UnitScaleFactor()); + out->mMetaData->Set(9, "OriginalUnitScaleFactor", doc.GlobalSettings().OriginalUnitScaleFactor()); + out->mMetaData->Set(10, "AmbientColor", doc.GlobalSettings().AmbientColor()); + out->mMetaData->Set(11, "FrameRate", (int)doc.GlobalSettings().TimeMode()); + out->mMetaData->Set(12, "TimeSpanStart", doc.GlobalSettings().TimeSpanStart()); + out->mMetaData->Set(13, "TimeSpanStop", doc.GlobalSettings().TimeSpanStop()); + out->mMetaData->Set(14, "CustomFrameRate", doc.GlobalSettings().CustomFrameRate()); + } + + void FBXConverter::TransferDataToScene() + { + ai_assert(!out->mMeshes); + ai_assert(!out->mNumMeshes); + + // note: the trailing () ensures initialization with NULL - not + // many C++ users seem to know this, so pointing it out to avoid + // confusion why this code works. + + if (meshes.size()) { + out->mMeshes = new aiMesh*[meshes.size()](); + out->mNumMeshes = static_cast(meshes.size()); + + std::swap_ranges(meshes.begin(), meshes.end(), out->mMeshes); + } + + if (materials.size()) { + out->mMaterials = new aiMaterial*[materials.size()](); + out->mNumMaterials = static_cast(materials.size()); + + std::swap_ranges(materials.begin(), materials.end(), out->mMaterials); + } + + if (animations.size()) { + out->mAnimations = new aiAnimation*[animations.size()](); + out->mNumAnimations = static_cast(animations.size()); + + std::swap_ranges(animations.begin(), animations.end(), out->mAnimations); + } + + if (lights.size()) { + out->mLights = new aiLight*[lights.size()](); + out->mNumLights = static_cast(lights.size()); + + std::swap_ranges(lights.begin(), lights.end(), out->mLights); + } + + if (cameras.size()) { + out->mCameras = new aiCamera*[cameras.size()](); + out->mNumCameras = static_cast(cameras.size()); + + std::swap_ranges(cameras.begin(), cameras.end(), out->mCameras); + } + + if (textures.size()) { + out->mTextures = new aiTexture*[textures.size()](); + out->mNumTextures = static_cast(textures.size()); + + std::swap_ranges(textures.begin(), textures.end(), out->mTextures); + } + } + + // ------------------------------------------------------------------------------------------------ + void ConvertToAssimpScene(aiScene* out, const Document& doc, bool removeEmptyBones) + { + FBXConverter converter(out, doc, removeEmptyBones); + } + + } // !FBX +} // !Assimp + +#endif diff --git a/third_party/libassimp/code/FBXConverter.h b/third_party/libassimp/code/FBX/FBXConverter.h similarity index 90% rename from third_party/libassimp/code/FBXConverter.h rename to third_party/libassimp/code/FBX/FBXConverter.h index ca8dcba2e4..77ced1950c 100644 --- a/third_party/libassimp/code/FBXConverter.h +++ b/third_party/libassimp/code/FBX/FBXConverter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -52,30 +52,37 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "FBXUtil.h" #include "FBXProperties.h" #include "FBXImporter.h" + #include #include #include #include #include #include +#include +#include struct aiScene; struct aiNode; struct aiMaterial; +struct morphKeyData { + std::vector values; + std::vector weights; +}; +typedef std::map morphAnimData; + namespace Assimp { namespace FBX { class Document; - -using NodeNameCache = std::set; - /** * Convert a FBX #Document to #aiScene * @param out Empty scene to be populated - * @param doc Parsed FBX document + * @param doc Parsed FBX document + * @param removeEmptyBones Will remove bones, which do not have any references to vertices. */ -void ConvertToAssimpScene(aiScene* out, const Document& doc); +void ConvertToAssimpScene(aiScene* out, const Document& doc, bool removeEmptyBones); /** Dummy class to encapsulate the conversion process */ class FBXConverter { @@ -106,7 +113,7 @@ public: }; public: - FBXConverter(aiScene* out, const Document& doc); + FBXConverter(aiScene* out, const Document& doc, bool removeEmptyBones); ~FBXConverter(); private: @@ -138,6 +145,11 @@ private: // while these would be allowed, they are a potential trouble spot so better not use them). const char* NameTransformationComp(TransformationComp comp); + // ------------------------------------------------------------------------------------------------ + // Returns an unique name for a node or traverses up a hierarchy until a non-empty name is found and + // then makes this name unique + std::string MakeUniqueNodeName(const Model* const model, const aiNode& parent); + // ------------------------------------------------------------------------------------------------ // note: this returns the REAL fbx property names const char* NameTransformationCompProperty(TransformationComp comp); @@ -161,21 +173,25 @@ private: /** * note: memory for output_nodes will be managed by the caller */ - void GenerateTransformationNodeChain(const Model& model, std::vector& output_nodes, std::vector& post_output_nodes); + bool GenerateTransformationNodeChain(const Model& model, const std::string& name, std::vector& output_nodes, std::vector& post_output_nodes); // ------------------------------------------------------------------------------------------------ void SetupNodeMetadata(const Model& model, aiNode& nd); // ------------------------------------------------------------------------------------------------ void ConvertModel(const Model& model, aiNode& nd, const aiMatrix4x4& node_global_transform); - + // ------------------------------------------------------------------------------------------------ // MeshGeometry -> aiMesh, return mesh index + 1 or 0 if the conversion failed std::vector ConvertMesh(const MeshGeometry& mesh, const Model& model, const aiMatrix4x4& node_global_transform, aiNode& nd); // ------------------------------------------------------------------------------------------------ - aiMesh* SetupEmptyMesh(const MeshGeometry& mesh, aiNode& nd); + std::vector ConvertLine(const LineGeometry& line, const Model& model, + const aiMatrix4x4& node_global_transform, aiNode& nd); + + // ------------------------------------------------------------------------------------------------ + aiMesh* SetupEmptyMesh(const Geometry& mesh, aiNode& nd); // ------------------------------------------------------------------------------------------------ unsigned int ConvertMeshSingleMaterial(const MeshGeometry& mesh, const Model& model, @@ -258,6 +274,7 @@ private: // ------------------------------------------------------------------------------------------------ void SetShadingPropertiesCommon(aiMaterial* out_mat, const PropertyTable& props); + void SetShadingPropertiesRaw(aiMaterial* out_mat, const PropertyTable& props, const TextureMap& textures, const MeshGeometry* const mesh); // ------------------------------------------------------------------------------------------------ // get the number of fps for a FrameRate enumerated value @@ -272,6 +289,7 @@ private: // the function is guaranteed to provide consistent results over multiple invocations // UNLESS RenameNode() is called for a particular node name. std::string FixNodeName(const std::string& name); + std::string FixAnimMeshName(const std::string& name); typedef std::map LayerMap; @@ -281,6 +299,9 @@ private: // ------------------------------------------------------------------------------------------------ void ConvertAnimationStack(const AnimationStack& st); + // ------------------------------------------------------------------------------------------------ + void ProcessMorphAnimDatas(std::map* morphAnimDatas, const BlendShapeChannel* bsc, const AnimationCurveNode* node); + // ------------------------------------------------------------------------------------------------ void GenerateNodeAnimations(std::vector& node_anims, const std::string& fixed_name, @@ -404,7 +425,6 @@ private: void TransferDataToScene(); private: - // 0: not assigned yet, others: index is value - 1 unsigned int defaultMaterialIndex; @@ -415,20 +435,23 @@ private: std::vector cameras; std::vector textures; - typedef std::map MaterialMap; + using MaterialMap = std::map; MaterialMap materials_converted; - typedef std::map VideoMap; + using VideoMap = std::map; VideoMap textures_converted; - typedef std::map > MeshMap; + using MeshMap = std::map >; MeshMap meshes_converted; // fixed node name -> which trafo chain components have animations? - typedef std::map NodeAnimBitMap; + using NodeAnimBitMap = std::map ; NodeAnimBitMap node_anim_chain_bits; + // number of nodes with the same name + using NodeNameCache = std::unordered_map; NodeNameCache mNodeNames; + double anim_fps; aiScene* const out; diff --git a/third_party/libassimp/code/FBXDeformer.cpp b/third_party/libassimp/code/FBX/FBXDeformer.cpp similarity index 70% rename from third_party/libassimp/code/FBXDeformer.cpp rename to third_party/libassimp/code/FBX/FBXDeformer.cpp index 9c7c7a4c47..6927553450 100644 --- a/third_party/libassimp/code/FBXDeformer.cpp +++ b/third_party/libassimp/code/FBX/FBXDeformer.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -48,6 +48,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "FBXParser.h" #include "FBXDocument.h" +#include "FBXMeshGeometry.h" #include "FBXImporter.h" #include "FBXDocumentUtil.h" @@ -158,9 +159,55 @@ Skin::~Skin() { } +// ------------------------------------------------------------------------------------------------ +BlendShape::BlendShape(uint64_t id, const Element& element, const Document& doc, const std::string& name) + : Deformer(id, element, doc, name) +{ + const std::vector& conns = doc.GetConnectionsByDestinationSequenced(ID(), "Deformer"); + blendShapeChannels.reserve(conns.size()); + for (const Connection* con : conns) { + const BlendShapeChannel* const bspc = ProcessSimpleConnection(*con, false, "BlendShapeChannel -> BlendShape", element); + if (bspc) { + blendShapeChannels.push_back(bspc); + continue; + } + } +} +// ------------------------------------------------------------------------------------------------ +BlendShape::~BlendShape() +{ } +// ------------------------------------------------------------------------------------------------ +BlendShapeChannel::BlendShapeChannel(uint64_t id, const Element& element, const Document& doc, const std::string& name) + : Deformer(id, element, doc, name) +{ + const Scope& sc = GetRequiredScope(element); + const Element* const DeformPercent = sc["DeformPercent"]; + if (DeformPercent) { + percent = ParseTokenAsFloat(GetRequiredToken(*DeformPercent, 0)); + } + const Element* const FullWeights = sc["FullWeights"]; + if (FullWeights) { + ParseVectorDataArray(fullWeights, *FullWeights); + } + const std::vector& conns = doc.GetConnectionsByDestinationSequenced(ID(), "Geometry"); + shapeGeometries.reserve(conns.size()); + for (const Connection* con : conns) { + const ShapeGeometry* const sg = ProcessSimpleConnection(*con, false, "Shape -> BlendShapeChannel", element); + if (sg) { + shapeGeometries.push_back(sg); + continue; + } + } } +// ------------------------------------------------------------------------------------------------ +BlendShapeChannel::~BlendShapeChannel() +{ +} +// ------------------------------------------------------------------------------------------------ +} +} #endif diff --git a/third_party/libassimp/code/FBXDocument.cpp b/third_party/libassimp/code/FBX/FBXDocument.cpp similarity index 97% rename from third_party/libassimp/code/FBXDocument.cpp rename to third_party/libassimp/code/FBX/FBXDocument.cpp index f53ae44052..506fd978dd 100644 --- a/third_party/libassimp/code/FBXDocument.cpp +++ b/third_party/libassimp/code/FBX/FBXDocument.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -69,8 +69,7 @@ LazyObject::LazyObject(uint64_t id, const Element& element, const Document& doc) : doc(doc) , element(element) , id(id) -, flags() -{ +, flags() { // empty } @@ -84,21 +83,13 @@ LazyObject::~LazyObject() const Object* LazyObject::Get(bool dieOnError) { if(IsBeingConstructed() || FailedToConstruct()) { - return NULL; + return nullptr; } if (object.get()) { return object.get(); } - // if this is the root object, we return a dummy since there - // is no root object int he fbx file - it is just referenced - // with id 0. - if(id == 0L) { - object.reset(new Object(id, element, "Model::RootNode")); - return object.get(); - } - const Token& key = element.KeyToken(); const TokenList& tokens = element.Tokens(); @@ -146,6 +137,12 @@ const Object* LazyObject::Get(bool dieOnError) if (!strcmp(classtag.c_str(),"Mesh")) { object.reset(new MeshGeometry(id,element,name,doc)); } + if (!strcmp(classtag.c_str(), "Shape")) { + object.reset(new ShapeGeometry(id, element, name, doc)); + } + if (!strcmp(classtag.c_str(), "Line")) { + object.reset(new LineGeometry(id, element, name, doc)); + } } else if (!strncmp(obtype,"NodeAttribute",length)) { if (!strcmp(classtag.c_str(),"Camera")) { @@ -171,6 +168,12 @@ const Object* LazyObject::Get(bool dieOnError) else if (!strcmp(classtag.c_str(),"Skin")) { object.reset(new Skin(id,element,doc,name)); } + else if (!strcmp(classtag.c_str(), "BlendShape")) { + object.reset(new BlendShape(id, element, doc, name)); + } + else if (!strcmp(classtag.c_str(), "BlendShapeChannel")) { + object.reset(new BlendShapeChannel(id, element, doc, name)); + } } else if ( !strncmp( obtype, "Model", length ) ) { // FK and IK effectors are not supported @@ -541,7 +544,7 @@ const std::vector& Document::AnimationStacks() const LazyObject* Document::GetObject(uint64_t id) const { ObjectMap::const_iterator it = objects.find(id); - return it == objects.end() ? NULL : (*it).second; + return it == objects.end() ? nullptr : (*it).second; } #define MAX_CLASSNAMES 6 @@ -598,7 +601,7 @@ std::vector Document::GetConnectionsSequenced(uint64_t id, bo for (size_t i = 0; i < c; ++i) { ai_assert(classnames[i]); if(static_cast(std::distance(key.begin(),key.end())) == lengths[i] && !strncmp(classnames[i],obtype,lengths[i])) { - obtype = NULL; + obtype = nullptr; break; } } diff --git a/third_party/libassimp/code/FBXDocument.h b/third_party/libassimp/code/FBX/FBXDocument.h similarity index 93% rename from third_party/libassimp/code/FBXDocument.h rename to third_party/libassimp/code/FBX/FBXDocument.h index 654f5bfa8d..18e5c38f13 100644 --- a/third_party/libassimp/code/FBXDocument.h +++ b/third_party/libassimp/code/FBX/FBXDocument.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -65,6 +65,8 @@ struct ImportSettings; class PropertyTable; class Document; class Material; +class ShapeGeometry; +class LineGeometry; class Geometry; class Video; @@ -74,6 +76,8 @@ class AnimationCurveNode; class AnimationLayer; class AnimationStack; +class BlendShapeChannel; +class BlendShape; class Skin; class Cluster; @@ -81,13 +85,11 @@ class Cluster; /** Represents a delay-parsed FBX objects. Many objects in the scene * are not needed by assimp, so it makes no sense to parse them * upfront. */ -class LazyObject -{ +class LazyObject { public: LazyObject(uint64_t id, const Element& element, const Document& doc); - ~LazyObject(); -public: + ~LazyObject(); const Object* Get(bool dieOnError = false); @@ -132,11 +134,8 @@ private: unsigned int flags; }; - - /** Base class for in-memory (DOM) representations of FBX objects */ -class Object -{ +class Object { public: Object(uint64_t id, const Element& element, const std::string& name); @@ -160,14 +159,12 @@ protected: const uint64_t id; }; - - /** DOM class for generic FBX NoteAttribute blocks. NoteAttribute's just hold a property table, * fixed members are added by deriving classes. */ -class NodeAttribute : public Object -{ +class NodeAttribute : public Object { public: NodeAttribute(uint64_t id, const Element& element, const Document& doc, const std::string& name); + virtual ~NodeAttribute(); const PropertyTable& Props() const { @@ -179,12 +176,11 @@ private: std::shared_ptr props; }; - /** DOM base class for FBX camera settings attached to a node */ -class CameraSwitcher : public NodeAttribute -{ +class CameraSwitcher : public NodeAttribute { public: CameraSwitcher(uint64_t id, const Element& element, const Document& doc, const std::string& name); + virtual ~CameraSwitcher(); int CameraID() const { @@ -205,7 +201,6 @@ private: std::string cameraIndexName; }; - #define fbx_stringize(a) #a #define fbx_simple_property(name, type, default_value) \ @@ -226,13 +221,12 @@ private: /** DOM base class for FBX cameras attached to a node */ -class Camera : public NodeAttribute -{ +class Camera : public NodeAttribute { public: Camera(uint64_t id, const Element& element, const Document& doc, const std::string& name); + virtual ~Camera(); -public: fbx_simple_property(Position, aiVector3D, aiVector3D(0,0,0)) fbx_simple_property(UpVector, aiVector3D, aiVector3D(0,1,0)) fbx_simple_property(InterestPosition, aiVector3D, aiVector3D(0,0,0)) @@ -252,33 +246,26 @@ public: fbx_simple_property(FocalLength, float, 1.0f) }; - /** DOM base class for FBX null markers attached to a node */ -class Null : public NodeAttribute -{ +class Null : public NodeAttribute { public: Null(uint64_t id, const Element& element, const Document& doc, const std::string& name); virtual ~Null(); }; - /** DOM base class for FBX limb node markers attached to a node */ -class LimbNode : public NodeAttribute -{ +class LimbNode : public NodeAttribute { public: LimbNode(uint64_t id, const Element& element, const Document& doc, const std::string& name); virtual ~LimbNode(); }; - /** DOM base class for FBX lights attached to a node */ -class Light : public NodeAttribute -{ +class Light : public NodeAttribute { public: Light(uint64_t id, const Element& element, const Document& doc, const std::string& name); virtual ~Light(); -public: enum Type { Type_Point, @@ -300,7 +287,6 @@ public: Decay_MAX // end-of-enum sentinel }; -public: fbx_simple_property(Color, aiVector3D, aiVector3D(1,1,1)) fbx_simple_enum_property(LightType, Type, 0) fbx_simple_property(CastLightOnObject, bool, false) @@ -334,10 +320,8 @@ public: fbx_simple_property(EnableBarnDoor, bool, true) }; - /** DOM base class for FBX models (even though its semantics are more "node" than "model" */ -class Model : public Object -{ +class Model : public Object { public: enum RotOrder { RotOrder_EulerXYZ = 0, @@ -352,7 +336,6 @@ public: RotOrder_MAX // end-of-enum sentinel }; - enum TransformInheritance { TransformInheritance_RrSs = 0, TransformInheritance_RSrs, @@ -486,13 +469,12 @@ private: }; /** DOM class for generic FBX textures */ -class Texture : public Object -{ +class Texture : public Object { public: Texture(uint64_t id, const Element& element, const Document& doc, const std::string& name); + virtual ~Texture(); -public: const std::string& Type() const { return type; } @@ -547,17 +529,15 @@ private: }; /** DOM class for layered FBX textures */ -class LayeredTexture : public Object -{ +class LayeredTexture : public Object { public: LayeredTexture(uint64_t id, const Element& element, const Document& doc, const std::string& name); virtual ~LayeredTexture(); - //Can only be called after construction of the layered texture object due to construction flag. + // Can only be called after construction of the layered texture object due to construction flag. void fillTexture(const Document& doc); - enum BlendMode - { + enum BlendMode { BlendMode_Translucent, BlendMode_Additive, BlendMode_Modulate, @@ -619,13 +599,12 @@ typedef std::fbx_unordered_map LayeredTextur /** DOM class for generic FBX videos */ -class Video : public Object -{ +class Video : public Object { public: Video(uint64_t id, const Element& element, const Document& doc, const std::string& name); + virtual ~Video(); -public: const std::string& Type() const { return type; } @@ -648,7 +627,7 @@ public: return content; } - uint32_t ContentLength() const { + uint64_t ContentLength() const { return contentLength; } @@ -664,15 +643,15 @@ private: std::string fileName; std::shared_ptr props; - uint32_t contentLength; + uint64_t contentLength; uint8_t* content; }; /** DOM class for generic FBX materials */ -class Material : public Object -{ +class Material : public Object { public: Material(uint64_t id, const Element& element, const Document& doc, const std::string& name); + virtual ~Material(); const std::string& GetShadingModel() const { @@ -709,8 +688,7 @@ typedef std::vector KeyTimeList; typedef std::vector KeyValueList; /** Represents a FBX animation curve (i.e. a 1-dimensional set of keyframes and values therefor) */ -class AnimationCurve : public Object -{ +class AnimationCurve : public Object { public: AnimationCurve(uint64_t id, const Element& element, const std::string& name, const Document& doc); virtual ~AnimationCurve(); @@ -721,14 +699,12 @@ public: return keys; } - /** get list of keyframe values. * Invariant: |GetKeys()| == |GetValues()| && |GetKeys()| > 0*/ const KeyValueList& GetValues() const { return values; } - const std::vector& GetAttributes() const { return attributes; } @@ -747,10 +723,8 @@ private: // property-name -> animation curve typedef std::map AnimationCurveMap; - /** Represents a FBX animation curve (i.e. a mapping from single animation curves to nodes) */ -class AnimationCurveNode : public Object -{ +class AnimationCurveNode : public Object { public: /* the optional white list specifies a list of property names for which the caller wants animations for. If the curve node does not match one of these, std::range_error @@ -800,8 +774,7 @@ private: typedef std::vector AnimationCurveNodeList; /** Represents a FBX animation layer (i.e. a list of node animations) */ -class AnimationLayer : public Object -{ +class AnimationLayer : public Object { public: AnimationLayer(uint64_t id, const Element& element, const std::string& name, const Document& doc); virtual ~AnimationLayer(); @@ -814,7 +787,7 @@ public: /* the optional white list specifies a list of property names for which the caller wants animations for. Curves not matching this list will not be added to the animation layer. */ - AnimationCurveNodeList Nodes(const char* const * target_prop_whitelist = NULL, size_t whitelist_size = 0) const; + AnimationCurveNodeList Nodes(const char* const * target_prop_whitelist = nullptr, size_t whitelist_size = 0) const; private: std::shared_ptr props; @@ -824,8 +797,7 @@ private: typedef std::vector AnimationLayerList; /** Represents a FBX animation stack (i.e. a list of animation layers) */ -class AnimationStack : public Object -{ +class AnimationStack : public Object { public: AnimationStack(uint64_t id, const Element& element, const std::string& name, const Document& doc); virtual ~AnimationStack(); @@ -851,8 +823,7 @@ private: /** DOM class for deformers */ -class Deformer : public Object -{ +class Deformer : public Object { public: Deformer(uint64_t id, const Element& element, const Document& doc, const std::string& name); virtual ~Deformer(); @@ -869,11 +840,52 @@ private: typedef std::vector WeightArray; typedef std::vector WeightIndexArray; -/** DOM class for skin deformer clusters (aka subdeformers) */ -class Cluster : public Deformer -{ + +/** DOM class for BlendShapeChannel deformers */ +class BlendShapeChannel : public Deformer { +public: + BlendShapeChannel(uint64_t id, const Element& element, const Document& doc, const std::string& name); + + virtual ~BlendShapeChannel(); + + float DeformPercent() const { + return percent; + } + + const WeightArray& GetFullWeights() const { + return fullWeights; + } + + const std::vector& GetShapeGeometries() const { + return shapeGeometries; + } + +private: + float percent; + WeightArray fullWeights; + std::vector shapeGeometries; +}; + +/** DOM class for BlendShape deformers */ +class BlendShape : public Deformer { +public: + BlendShape(uint64_t id, const Element& element, const Document& doc, const std::string& name); + + virtual ~BlendShape(); + + const std::vector& BlendShapeChannels() const { + return blendShapeChannels; + } + +private: + std::vector blendShapeChannels; +}; + +/** DOM class for skin deformer clusters (aka sub-deformers) */ +class Cluster : public Deformer { public: Cluster(uint64_t id, const Element& element, const Document& doc, const std::string& name); + virtual ~Cluster(); /** get the list of deformer weights associated with this cluster. @@ -914,10 +926,10 @@ private: }; /** DOM class for skin deformers */ -class Skin : public Deformer -{ +class Skin : public Deformer { public: Skin(uint64_t id, const Element& element, const Document& doc, const std::string& name); + virtual ~Skin(); float DeformAccuracy() const { @@ -934,10 +946,10 @@ private: }; /** Represents a link between two FBX objects. */ -class Connection -{ +class Connection { public: Connection(uint64_t insertionOrder, uint64_t src, uint64_t dest, const std::string& prop, const Document& doc); + ~Connection(); // note: a connection ensures that the source and dest objects exist, but @@ -962,7 +974,7 @@ public: } int CompareTo(const Connection* c) const { - ai_assert( NULL != c ); + ai_assert( nullptr != c ); // note: can't subtract because this would overflow uint64_t if(InsertionOrder() > c->InsertionOrder()) { @@ -975,7 +987,7 @@ public: } bool Compare(const Connection* c) const { - ai_assert( NULL != c ); + ai_assert( nullptr != c ); return InsertionOrder() < c->InsertionOrder(); } @@ -1003,6 +1015,7 @@ typedef std::multimap ConnectionMap; class FileGlobalSettings { public: FileGlobalSettings(const Document& doc, std::shared_ptr props); + ~FileGlobalSettings(); const PropertyTable& Props() const { @@ -1059,10 +1072,10 @@ private: }; /** DOM root for a FBX file */ -class Document -{ +class Document { public: Document(const Parser& parser, const ImportSettings& settings); + ~Document(); LazyObject* GetObject(uint64_t id) const; diff --git a/third_party/libassimp/code/FBXDocumentUtil.cpp b/third_party/libassimp/code/FBX/FBXDocumentUtil.cpp similarity index 99% rename from third_party/libassimp/code/FBXDocumentUtil.cpp rename to third_party/libassimp/code/FBX/FBXDocumentUtil.cpp index 6f1e18e42d..f84691479a 100644 --- a/third_party/libassimp/code/FBXDocumentUtil.cpp +++ b/third_party/libassimp/code/FBX/FBXDocumentUtil.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/FBXDocumentUtil.h b/third_party/libassimp/code/FBX/FBXDocumentUtil.h similarity index 95% rename from third_party/libassimp/code/FBXDocumentUtil.h rename to third_party/libassimp/code/FBX/FBXDocumentUtil.h index c0435a6630..2450109e59 100644 --- a/third_party/libassimp/code/FBXDocumentUtil.h +++ b/third_party/libassimp/code/FBX/FBXDocumentUtil.h @@ -56,7 +56,6 @@ namespace Assimp { namespace FBX { namespace Util { - /* DOM/Parse error reporting - does not return */ AI_WONT_RETURN void DOMError(const std::string& message, const Token& token) AI_WONT_RETURN_SUFFIX; AI_WONT_RETURN void DOMError(const std::string& message, const Element* element = NULL) AI_WONT_RETURN_SUFFIX; @@ -73,28 +72,28 @@ std::shared_ptr GetPropertyTable(const Document& doc, const Scope& sc, bool no_warn = false); - // ------------------------------------------------------------------------------------------------ template -inline const T* ProcessSimpleConnection(const Connection& con, +inline +const T* ProcessSimpleConnection(const Connection& con, bool is_object_property_conn, const char* name, const Element& element, - const char** propNameOut = NULL) + const char** propNameOut = nullptr) { if (is_object_property_conn && !con.PropertyName().length()) { DOMWarning("expected incoming " + std::string(name) + " link to be an object-object connection, ignoring", &element ); - return NULL; + return nullptr; } else if (!is_object_property_conn && con.PropertyName().length()) { DOMWarning("expected incoming " + std::string(name) + " link to be an object-property connection, ignoring", &element ); - return NULL; + return nullptr; } if(is_object_property_conn && propNameOut) { @@ -108,13 +107,12 @@ inline const T* ProcessSimpleConnection(const Connection& con, DOMWarning("failed to read source object for incoming " + std::string(name) + " link, ignoring", &element); - return NULL; + return nullptr; } return dynamic_cast(ob); } - } //!Util } //!FBX } //!Assimp diff --git a/third_party/libassimp/code/FBXExportNode.cpp b/third_party/libassimp/code/FBX/FBXExportNode.cpp similarity index 97% rename from third_party/libassimp/code/FBXExportNode.cpp rename to third_party/libassimp/code/FBX/FBXExportNode.cpp index a1171eca84..06c89cee46 100644 --- a/third_party/libassimp/code/FBXExportNode.cpp +++ b/third_party/libassimp/code/FBX/FBXExportNode.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -54,6 +54,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include // ostringstream #include // shared_ptr +namespace Assimp { // AddP70 helpers... there's no usable pattern here, // so all are defined as separate functions. // Even "animatable" properties are often completely different @@ -252,7 +253,8 @@ void FBX::Node::DumpChildren( } else { std::ostringstream ss; DumpChildrenAscii(ss, indent); - s.PutString(ss.str()); + if (ss.tellp() > 0) + s.PutString(ss.str()); } } @@ -266,7 +268,8 @@ void FBX::Node::End( } else { std::ostringstream ss; EndAscii(ss, indent, has_children); - s.PutString(ss.str()); + if (ss.tellp() > 0) + s.PutString(ss.str()); } } @@ -367,7 +370,7 @@ void FBX::Node::EndBinary( bool has_children ) { // if there were children, add a null record - if (has_children) { s.PutString(FBX::NULL_RECORD); } + if (has_children) { s.PutString(Assimp::FBX::NULL_RECORD); } // now go back and write initial pos this->end_pos = s.Tell(); @@ -432,7 +435,7 @@ void FBX::Node::WritePropertyNodeAscii( char buffer[32]; FBX::Node node(name); node.Begin(s, false, indent); - std::string vsize = std::to_string(v.size()); + std::string vsize = to_string(v.size()); // * { s.PutChar('*'); s.PutString(vsize); s.PutString(" {\n"); // indent + 1 @@ -468,7 +471,7 @@ void FBX::Node::WritePropertyNodeAscii( char buffer[32]; FBX::Node node(name); node.Begin(s, false, indent); - std::string vsize = std::to_string(v.size()); + std::string vsize = to_string(v.size()); // * { s.PutChar('*'); s.PutString(vsize); s.PutString(" {\n"); // indent + 1 @@ -563,6 +566,6 @@ void FBX::Node::WritePropertyNode( FBX::Node::WritePropertyNodeAscii(name, v, s, indent); } } - +} #endif // ASSIMP_BUILD_NO_FBX_EXPORTER #endif // ASSIMP_BUILD_NO_EXPORT diff --git a/third_party/libassimp/code/FBXExportNode.h b/third_party/libassimp/code/FBX/FBXExportNode.h similarity index 94% rename from third_party/libassimp/code/FBXExportNode.h rename to third_party/libassimp/code/FBX/FBXExportNode.h index 5ddd8c77b3..ef3bc781a4 100644 --- a/third_party/libassimp/code/FBXExportNode.h +++ b/third_party/libassimp/code/FBX/FBXExportNode.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -54,30 +54,43 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include +namespace Assimp { namespace FBX { class Node; } -class FBX::Node -{ -public: // public data members +class FBX::Node { +public: // TODO: accessors std::string name; // node name - std::vector properties; // node properties + std::vector properties; // node properties std::vector children; // child nodes // some nodes always pretend they have children... bool force_has_children = false; public: // constructors + /// The default class constructor. Node() = default; - Node(const std::string& n) : name(n) {} + + /// The class constructor with the name. + Node(const std::string& n) + : name(n) + , properties() + , children() + , force_has_children( false ) { + // empty + } // convenience template to construct with properties directly template Node(const std::string& n, const More... more) - : name(n) - { AddProperties(more...); } + : name(n) + , properties() + , children() + , force_has_children(false) { + AddProperties(more...); + } public: // functions to add properties or children // add a single property to the node @@ -201,7 +214,7 @@ public: // static member functions Assimp::StreamWriterLE& s, bool binary, int indent ) { - FBX::Property p(value); + FBX::FBXExportProperty p(value); FBX::Node node(name, p); node.Dump(s, binary, indent); } @@ -251,7 +264,7 @@ private: // static helper functions ); }; - +} #endif // ASSIMP_BUILD_NO_FBX_EXPORTER diff --git a/third_party/libassimp/code/FBXExportProperty.cpp b/third_party/libassimp/code/FBX/FBXExportProperty.cpp similarity index 60% rename from third_party/libassimp/code/FBXExportProperty.cpp rename to third_party/libassimp/code/FBX/FBXExportProperty.cpp index 4317502741..f2a63b72b9 100644 --- a/third_party/libassimp/code/FBXExportProperty.cpp +++ b/third_party/libassimp/code/FBX/FBXExportProperty.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -52,187 +52,206 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include // ostringstream +namespace Assimp { +namespace FBX { // constructors for single element properties -FBX::Property::Property(bool v) - : type('C'), data(1) -{ - data = {uint8_t(v)}; -} +FBXExportProperty::FBXExportProperty(bool v) +: type('C') +, data(1, uint8_t(v)) {} -FBX::Property::Property(int16_t v) : type('Y'), data(2) -{ +FBXExportProperty::FBXExportProperty(int16_t v) +: type('Y') +, data(2) { uint8_t* d = data.data(); (reinterpret_cast(d))[0] = v; } -FBX::Property::Property(int32_t v) : type('I'), data(4) -{ +FBXExportProperty::FBXExportProperty(int32_t v) +: type('I') +, data(4) { uint8_t* d = data.data(); (reinterpret_cast(d))[0] = v; } -FBX::Property::Property(float v) : type('F'), data(4) -{ +FBXExportProperty::FBXExportProperty(float v) +: type('F') +, data(4) { uint8_t* d = data.data(); (reinterpret_cast(d))[0] = v; } -FBX::Property::Property(double v) : type('D'), data(8) -{ +FBXExportProperty::FBXExportProperty(double v) +: type('D') +, data(8) { uint8_t* d = data.data(); (reinterpret_cast(d))[0] = v; } -FBX::Property::Property(int64_t v) : type('L'), data(8) -{ +FBXExportProperty::FBXExportProperty(int64_t v) +: type('L') +, data(8) { uint8_t* d = data.data(); (reinterpret_cast(d))[0] = v; } - // constructors for array-type properties -FBX::Property::Property(const char* c, bool raw) - : Property(std::string(c), raw) -{} +FBXExportProperty::FBXExportProperty(const char* c, bool raw) +: FBXExportProperty(std::string(c), raw) { + // empty +} // strings can either be saved as "raw" (R) data, or "string" (S) data -FBX::Property::Property(const std::string& s, bool raw) - : type(raw ? 'R' : 'S'), data(s.size()) -{ +FBXExportProperty::FBXExportProperty(const std::string& s, bool raw) +: type(raw ? 'R' : 'S') +, data(s.size()) { for (size_t i = 0; i < s.size(); ++i) { data[i] = uint8_t(s[i]); } } -FBX::Property::Property(const std::vector& r) - : type('R'), data(r) -{} +FBXExportProperty::FBXExportProperty(const std::vector& r) +: type('R') +, data(r) { + // empty +} -FBX::Property::Property(const std::vector& va) - : type('i'), data(4*va.size()) -{ +FBXExportProperty::FBXExportProperty(const std::vector& va) +: type('i') +, data(4 * va.size() ) { int32_t* d = reinterpret_cast(data.data()); - for (size_t i = 0; i < va.size(); ++i) { d[i] = va[i]; } + for (size_t i = 0; i < va.size(); ++i) { + d[i] = va[i]; + } } -FBX::Property::Property(const std::vector& va) - : type('l'), data(8*va.size()) -{ +FBXExportProperty::FBXExportProperty(const std::vector& va) +: type('l') +, data(8 * va.size()) { int64_t* d = reinterpret_cast(data.data()); - for (size_t i = 0; i < va.size(); ++i) { d[i] = va[i]; } + for (size_t i = 0; i < va.size(); ++i) { + d[i] = va[i]; + } } -FBX::Property::Property(const std::vector& va) - : type('f'), data(4*va.size()) -{ +FBXExportProperty::FBXExportProperty(const std::vector& va) +: type('f') +, data(4 * va.size()) { float* d = reinterpret_cast(data.data()); - for (size_t i = 0; i < va.size(); ++i) { d[i] = va[i]; } + for (size_t i = 0; i < va.size(); ++i) { + d[i] = va[i]; + } } -FBX::Property::Property(const std::vector& va) - : type('d'), data(8*va.size()) -{ +FBXExportProperty::FBXExportProperty(const std::vector& va) +: type('d') +, data(8 * va.size()) { double* d = reinterpret_cast(data.data()); - for (size_t i = 0; i < va.size(); ++i) { d[i] = va[i]; } + for (size_t i = 0; i < va.size(); ++i) { + d[i] = va[i]; + } } -FBX::Property::Property(const aiMatrix4x4& vm) - : type('d'), data(8*16) -{ +FBXExportProperty::FBXExportProperty(const aiMatrix4x4& vm) +: type('d') +, data(8 * 16) { double* d = reinterpret_cast(data.data()); for (unsigned int c = 0; c < 4; ++c) { for (unsigned int r = 0; r < 4; ++r) { - d[4*c+r] = vm[r][c]; + d[4 * c + r] = vm[r][c]; } } } // public member functions -size_t FBX::Property::size() -{ +size_t FBXExportProperty::size() { switch (type) { - case 'C': case 'Y': case 'I': case 'F': case 'D': case 'L': - return data.size() + 1; - case 'S': case 'R': - return data.size() + 5; - case 'i': case 'd': - return data.size() + 13; - default: - throw DeadlyExportError("Requested size on property of unknown type"); + case 'C': + case 'Y': + case 'I': + case 'F': + case 'D': + case 'L': + return data.size() + 1; + case 'S': + case 'R': + return data.size() + 5; + case 'i': + case 'd': + return data.size() + 13; + default: + throw DeadlyExportError("Requested size on property of unknown type"); } } -void FBX::Property::DumpBinary(Assimp::StreamWriterLE &s) -{ +void FBXExportProperty::DumpBinary(Assimp::StreamWriterLE& s) { s.PutU1(type); uint8_t* d = data.data(); size_t N; switch (type) { - case 'C': s.PutU1(*(reinterpret_cast(d))); return; - case 'Y': s.PutI2(*(reinterpret_cast(d))); return; - case 'I': s.PutI4(*(reinterpret_cast(d))); return; - case 'F': s.PutF4(*(reinterpret_cast(d))); return; - case 'D': s.PutF8(*(reinterpret_cast(d))); return; - case 'L': s.PutI8(*(reinterpret_cast(d))); return; - case 'S': - case 'R': - s.PutU4(uint32_t(data.size())); - for (size_t i = 0; i < data.size(); ++i) { s.PutU1(data[i]); } - return; - case 'i': - N = data.size() / 4; - s.PutU4(uint32_t(N)); // number of elements - s.PutU4(0); // no encoding (1 would be zip-compressed) - // TODO: compress if large? - s.PutU4(uint32_t(data.size())); // data size - for (size_t i = 0; i < N; ++i) { - s.PutI4((reinterpret_cast(d))[i]); - } - return; - case 'l': - N = data.size() / 8; - s.PutU4(uint32_t(N)); // number of elements - s.PutU4(0); // no encoding (1 would be zip-compressed) - // TODO: compress if large? - s.PutU4(uint32_t(data.size())); // data size - for (size_t i = 0; i < N; ++i) { - s.PutI8((reinterpret_cast(d))[i]); - } - return; - case 'f': - N = data.size() / 4; - s.PutU4(uint32_t(N)); // number of elements - s.PutU4(0); // no encoding (1 would be zip-compressed) - // TODO: compress if large? - s.PutU4(uint32_t(data.size())); // data size - for (size_t i = 0; i < N; ++i) { - s.PutF4((reinterpret_cast(d))[i]); - } - return; - case 'd': - N = data.size() / 8; - s.PutU4(uint32_t(N)); // number of elements - s.PutU4(0); // no encoding (1 would be zip-compressed) - // TODO: compress if large? - s.PutU4(uint32_t(data.size())); // data size - for (size_t i = 0; i < N; ++i) { - s.PutF8((reinterpret_cast(d))[i]); - } - return; - default: - std::ostringstream err; - err << "Tried to dump property with invalid type '"; - err << type << "'!"; - throw DeadlyExportError(err.str()); + case 'C': s.PutU1(*(reinterpret_cast(d))); return; + case 'Y': s.PutI2(*(reinterpret_cast(d))); return; + case 'I': s.PutI4(*(reinterpret_cast(d))); return; + case 'F': s.PutF4(*(reinterpret_cast(d))); return; + case 'D': s.PutF8(*(reinterpret_cast(d))); return; + case 'L': s.PutI8(*(reinterpret_cast(d))); return; + case 'S': + case 'R': + s.PutU4(uint32_t(data.size())); + for (size_t i = 0; i < data.size(); ++i) { s.PutU1(data[i]); } + return; + case 'i': + N = data.size() / 4; + s.PutU4(uint32_t(N)); // number of elements + s.PutU4(0); // no encoding (1 would be zip-compressed) + // TODO: compress if large? + s.PutU4(uint32_t(data.size())); // data size + for (size_t i = 0; i < N; ++i) { + s.PutI4((reinterpret_cast(d))[i]); + } + return; + case 'l': + N = data.size() / 8; + s.PutU4(uint32_t(N)); // number of elements + s.PutU4(0); // no encoding (1 would be zip-compressed) + // TODO: compress if large? + s.PutU4(uint32_t(data.size())); // data size + for (size_t i = 0; i < N; ++i) { + s.PutI8((reinterpret_cast(d))[i]); + } + return; + case 'f': + N = data.size() / 4; + s.PutU4(uint32_t(N)); // number of elements + s.PutU4(0); // no encoding (1 would be zip-compressed) + // TODO: compress if large? + s.PutU4(uint32_t(data.size())); // data size + for (size_t i = 0; i < N; ++i) { + s.PutF4((reinterpret_cast(d))[i]); + } + return; + case 'd': + N = data.size() / 8; + s.PutU4(uint32_t(N)); // number of elements + s.PutU4(0); // no encoding (1 would be zip-compressed) + // TODO: compress if large? + s.PutU4(uint32_t(data.size())); // data size + for (size_t i = 0; i < N; ++i) { + s.PutF8((reinterpret_cast(d))[i]); + } + return; + default: + std::ostringstream err; + err << "Tried to dump property with invalid type '"; + err << type << "'!"; + throw DeadlyExportError(err.str()); } } -void FBX::Property::DumpAscii(Assimp::StreamWriterLE &outstream, int indent) -{ +void FBXExportProperty::DumpAscii(Assimp::StreamWriterLE& outstream, int indent) { std::ostringstream ss; ss.imbue(std::locale::classic()); ss.precision(15); // this seems to match official FBX SDK exports @@ -240,8 +259,7 @@ void FBX::Property::DumpAscii(Assimp::StreamWriterLE &outstream, int indent) outstream.PutString(ss.str()); } -void FBX::Property::DumpAscii(std::ostream& s, int indent) -{ +void FBXExportProperty::DumpAscii(std::ostream& s, int indent) { // no writing type... or anything. just shove it into the stream. uint8_t* d = data.data(); size_t N; @@ -360,5 +378,8 @@ void FBX::Property::DumpAscii(std::ostream& s, int indent) } } +} // Namespace FBX +} // Namespace Assimp + #endif // ASSIMP_BUILD_NO_FBX_EXPORTER #endif // ASSIMP_BUILD_NO_EXPORT diff --git a/third_party/libassimp/code/FBXExportProperty.h b/third_party/libassimp/code/FBX/FBXExportProperty.h similarity index 76% rename from third_party/libassimp/code/FBXExportProperty.h rename to third_party/libassimp/code/FBX/FBXExportProperty.h index cb3b0113f7..d692fe6ee3 100644 --- a/third_party/libassimp/code/FBXExportProperty.h +++ b/third_party/libassimp/code/FBX/FBXExportProperty.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -47,7 +47,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_FBX_EXPORTER - #include // aiMatrix4x4 #include // StreamWriterLE @@ -56,11 +55,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include // is_void +namespace Assimp { namespace FBX { - class Property; -} -/** FBX::Property +/** @brief FBX::Property * * Holds a value of any of FBX's recognized types, * each represented by a particular one-character code. @@ -78,35 +76,34 @@ namespace FBX { * S : string (array of 1-byte char) * R : raw data (array of bytes) */ -class FBX::Property -{ +class FBXExportProperty { public: // constructors for basic types. // all explicit to avoid accidental typecasting - explicit Property(bool v); + explicit FBXExportProperty(bool v); // TODO: determine if there is actually a byte type, // or if this always means . 'C' seems to imply , // so possibly the above was intended to represent both. - explicit Property(int16_t v); - explicit Property(int32_t v); - explicit Property(float v); - explicit Property(double v); - explicit Property(int64_t v); + explicit FBXExportProperty(int16_t v); + explicit FBXExportProperty(int32_t v); + explicit FBXExportProperty(float v); + explicit FBXExportProperty(double v); + explicit FBXExportProperty(int64_t v); // strings can either be stored as 'R' (raw) or 'S' (string) type - explicit Property(const char* c, bool raw=false); - explicit Property(const std::string& s, bool raw=false); - explicit Property(const std::vector& r); - explicit Property(const std::vector& va); - explicit Property(const std::vector& va); - explicit Property(const std::vector& va); - explicit Property(const std::vector& va); - explicit Property(const aiMatrix4x4& vm); + explicit FBXExportProperty(const char* c, bool raw = false); + explicit FBXExportProperty(const std::string& s, bool raw = false); + explicit FBXExportProperty(const std::vector& r); + explicit FBXExportProperty(const std::vector& va); + explicit FBXExportProperty(const std::vector& va); + explicit FBXExportProperty(const std::vector& va); + explicit FBXExportProperty(const std::vector& va); + explicit FBXExportProperty(const aiMatrix4x4& vm); // this will catch any type not defined above, // so that we don't accidentally convert something we don't want. // for example (const char*) --> (bool)... seriously wtf C++ template - explicit Property(T v) : type('X') { + explicit FBXExportProperty(T v) : type('X') { static_assert(std::is_void::value, "TRIED TO CREATE FBX PROPERTY WITH UNSUPPORTED TYPE, CHECK YOUR PROPERTY INSTANTIATION"); } // note: no line wrap so it appears verbatim on the compiler error @@ -114,9 +111,9 @@ public: size_t size(); // write this property node as binary data to the given stream - void DumpBinary(Assimp::StreamWriterLE &s); - void DumpAscii(Assimp::StreamWriterLE &s, int indent=0); - void DumpAscii(std::ostream &s, int indent=0); + void DumpBinary(Assimp::StreamWriterLE& s); + void DumpAscii(Assimp::StreamWriterLE& s, int indent = 0); + void DumpAscii(std::ostream& s, int indent = 0); // note: make sure the ostream is in classic "C" locale private: @@ -124,6 +121,9 @@ private: std::vector data; }; +} // Namespace FBX +} // Namespace Assimp + #endif // ASSIMP_BUILD_NO_FBX_EXPORTER #endif // AI_FBXEXPORTPROPERTY_H_INC diff --git a/third_party/libassimp/code/FBXExporter.cpp b/third_party/libassimp/code/FBX/FBXExporter.cpp similarity index 91% rename from third_party/libassimp/code/FBXExporter.cpp rename to third_party/libassimp/code/FBX/FBXExporter.cpp index 037520641e..25d057df1c 100644 --- a/third_party/libassimp/code/FBXExporter.cpp +++ b/third_party/libassimp/code/FBX/FBXExporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -45,6 +45,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "FBXExportNode.h" #include "FBXExportProperty.h" #include "FBXCommon.h" +#include "FBXUtil.h" #include // aiGetVersion #include @@ -66,6 +67,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include +#include // RESOURCES: // https://code.blender.org/2013/08/fbx-binary-file-format-specification/ @@ -73,7 +75,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. const ai_real DEG = ai_real( 57.29577951308232087679815481 ); // degrees per radian +using namespace Assimp; +using namespace Assimp::FBX; + // some constants that we'll use for writing metadata +namespace Assimp { namespace FBX { const std::string EXPORT_VERSION_STR = "7.4.0"; const uint32_t EXPORT_VERSION_INT = 7400; // 7.4 == 2014/2015 @@ -92,11 +98,6 @@ namespace FBX { ";------------------------------------------------------------------"; } -using namespace Assimp; -using namespace FBX; - -namespace Assimp { - // --------------------------------------------------------------------- // Worker function for exporting a scene to binary FBX. // Prototyped and registered in Exporter.cpp @@ -121,6 +122,7 @@ namespace Assimp { IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties + ){ // initialize the exporter FBXExporter exporter(pScene, pProperties); @@ -131,13 +133,15 @@ namespace Assimp { } // end of namespace Assimp -FBXExporter::FBXExporter ( - const aiScene* pScene, - const ExportProperties* pProperties -) - : mScene(pScene) - , mProperties(pProperties) -{ +FBXExporter::FBXExporter ( const aiScene* pScene, const ExportProperties* pProperties ) +: binary(false) +, mScene(pScene) +, mProperties(pProperties) +, outfile() +, connections() +, mesh_uids() +, material_uids() +, node_uids() { // will probably need to determine UIDs, connections, etc here. // basically anything that needs to be known // before we start writing sections to the stream. @@ -1002,6 +1006,9 @@ void FBXExporter::WriteObjects () object_node.EndProperties(outstream, binary, indent); object_node.BeginChildren(outstream, binary, indent); + bool bJoinIdenticalVertices = mProperties->GetPropertyBool("bJoinIdenticalVertices", true); + std::vector> vVertexIndice;//save vertex_indices as it is needed later + // geometry (aiMesh) mesh_uids.clear(); indent = 1; @@ -1028,21 +1035,35 @@ void FBXExporter::WriteObjects () std::vector vertex_indices; // map of vertex value to its index in the data vector std::map index_by_vertex_value; - int32_t index = 0; - for (size_t vi = 0; vi < m->mNumVertices; ++vi) { - aiVector3D vtx = m->mVertices[vi]; - auto elem = index_by_vertex_value.find(vtx); - if (elem == index_by_vertex_value.end()) { - vertex_indices.push_back(index); - index_by_vertex_value[vtx] = index; - flattened_vertices.push_back(vtx[0]); - flattened_vertices.push_back(vtx[1]); - flattened_vertices.push_back(vtx[2]); - ++index; - } else { - vertex_indices.push_back(int32_t(elem->second)); + if(bJoinIdenticalVertices){ + int32_t index = 0; + for (size_t vi = 0; vi < m->mNumVertices; ++vi) { + aiVector3D vtx = m->mVertices[vi]; + auto elem = index_by_vertex_value.find(vtx); + if (elem == index_by_vertex_value.end()) { + vertex_indices.push_back(index); + index_by_vertex_value[vtx] = index; + flattened_vertices.push_back(vtx[0]); + flattened_vertices.push_back(vtx[1]); + flattened_vertices.push_back(vtx[2]); + ++index; + } else { + vertex_indices.push_back(int32_t(elem->second)); + } } } + else { // do not join vertex, respect the export flag + vertex_indices.resize(m->mNumVertices); + std::iota(vertex_indices.begin(), vertex_indices.end(), 0); + for(unsigned int v = 0; v < m->mNumVertices; ++ v) { + aiVector3D vtx = m->mVertices[v]; + flattened_vertices.push_back(vtx.x); + flattened_vertices.push_back(vtx.y); + flattened_vertices.push_back(vtx.z); + } + } + vVertexIndice.push_back(vertex_indices); + FBX::Node::WritePropertyNode( "Vertices", flattened_vertices, outstream, binary, indent ); @@ -1113,6 +1134,51 @@ void FBXExporter::WriteObjects () normals.End(outstream, binary, indent, true); } + // colors, if any + // TODO only one color channel currently + const int32_t colorChannelIndex = 0; + if (m->HasVertexColors(colorChannelIndex)) { + FBX::Node vertexcolors("LayerElementColor", int32_t(colorChannelIndex)); + vertexcolors.Begin(outstream, binary, indent); + vertexcolors.DumpProperties(outstream, binary, indent); + vertexcolors.EndProperties(outstream, binary, indent); + vertexcolors.BeginChildren(outstream, binary, indent); + indent = 3; + FBX::Node::WritePropertyNode( + "Version", int32_t(101), outstream, binary, indent + ); + char layerName[8]; + sprintf(layerName, "COLOR_%d", colorChannelIndex); + FBX::Node::WritePropertyNode( + "Name", (const char*)layerName, outstream, binary, indent + ); + FBX::Node::WritePropertyNode( + "MappingInformationType", "ByPolygonVertex", + outstream, binary, indent + ); + FBX::Node::WritePropertyNode( + "ReferenceInformationType", "Direct", + outstream, binary, indent + ); + std::vector color_data; + color_data.reserve(4 * polygon_data.size()); + for (size_t fi = 0; fi < m->mNumFaces; ++fi) { + const aiFace &f = m->mFaces[fi]; + for (size_t pvi = 0; pvi < f.mNumIndices; ++pvi) { + const aiColor4D &c = m->mColors[colorChannelIndex][f.mIndices[pvi]]; + color_data.push_back(c.r); + color_data.push_back(c.g); + color_data.push_back(c.b); + color_data.push_back(c.a); + } + } + FBX::Node::WritePropertyNode( + "Colors", color_data, outstream, binary, indent + ); + indent = 2; + vertexcolors.End(outstream, binary, indent, true); + } + // uvs, if any for (size_t uvi = 0; uvi < m->GetNumUVChannels(); ++uvi) { if (m->mNumUVComponents[uvi] > 2) { @@ -1206,6 +1272,11 @@ void FBXExporter::WriteObjects () le.AddChild("Type", "LayerElementNormal"); le.AddChild("TypedIndex", int32_t(0)); layer.AddChild(le); + // TODO only 1 color channel currently + le = FBX::Node("LayerElement"); + le.AddChild("Type", "LayerElementColor"); + le.AddChild("TypedIndex", int32_t(0)); + layer.AddChild(le); le = FBX::Node("LayerElement"); le.AddChild("Type", "LayerElementMaterial"); le.AddChild("TypedIndex", int32_t(0)); @@ -1216,6 +1287,16 @@ void FBXExporter::WriteObjects () layer.AddChild(le); layer.Dump(outstream, binary, indent); + for(unsigned int lr = 1; lr < m->GetNumUVChannels(); ++ lr) + { + FBX::Node layerExtra("Layer", int32_t(1)); + layerExtra.AddChild("Version", int32_t(100)); + FBX::Node leExtra("LayerElement"); + leExtra.AddChild("Type", "LayerElementUV"); + leExtra.AddChild("TypedIndex", int32_t(lr)); + layerExtra.AddChild(leExtra); + layerExtra.Dump(outstream, binary, indent); + } // finish the node record indent = 1; n.End(outstream, binary, indent, true); @@ -1391,10 +1472,6 @@ void FBXExporter::WriteObjects () // FbxVideo - stores images used by textures. for (const auto &it : uid_by_image) { - if (it.first.compare(0, 1, "*") == 0) { - // TODO: embedded textures - continue; - } FBX::Node n("Video"); const int64_t& uid = it.second; const std::string name = ""; // TODO: ... name??? @@ -1404,7 +1481,33 @@ void FBXExporter::WriteObjects () // TODO: get full path... relative path... etc... ugh... // for now just use the same path for everything, // and hopefully one of them will work out. - const std::string& path = it.first; + std::string path = it.first; + // try get embedded texture + const aiTexture* embedded_texture = mScene->GetEmbeddedTexture(it.first.c_str()); + if (embedded_texture != nullptr) { + // change the path (use original filename, if available. If name is empty, concatenate texture index with file extension) + std::stringstream newPath; + if (embedded_texture->mFilename.length > 0) { + newPath << embedded_texture->mFilename.C_Str(); + } else if (embedded_texture->achFormatHint[0]) { + int texture_index = std::stoi(path.substr(1, path.size() - 1)); + newPath << texture_index << "." << embedded_texture->achFormatHint; + } + path = newPath.str(); + // embed the texture + size_t texture_size = static_cast(embedded_texture->mWidth * std::max(embedded_texture->mHeight, 1u)); + if (binary) { + // embed texture as binary data + std::vector tex_data; + tex_data.resize(texture_size); + memcpy(&tex_data[0], (char*)embedded_texture->pcData, texture_size); + n.AddChild("Content", tex_data); + } else { + // embed texture in base64 encoding + std::string encoded_texture = FBX::Util::EncodeBase64((char*)embedded_texture->pcData, texture_size); + n.AddChild("Content", encoded_texture); + } + } p.AddP70("Path", "KString", "XRefUrl", "", path); n.AddChild(p); n.AddChild("UseMipMap", int32_t(0)); @@ -1417,17 +1520,17 @@ void FBXExporter::WriteObjects () // referenced by material_index/texture_type pairs. std::map,int64_t> texture_uids; const std::map prop_name_by_tt = { - {aiTextureType_DIFFUSE, "DiffuseColor"}, - {aiTextureType_SPECULAR, "SpecularColor"}, - {aiTextureType_AMBIENT, "AmbientColor"}, - {aiTextureType_EMISSIVE, "EmissiveColor"}, - {aiTextureType_HEIGHT, "Bump"}, - {aiTextureType_NORMALS, "NormalMap"}, - {aiTextureType_SHININESS, "ShininessExponent"}, - {aiTextureType_OPACITY, "TransparentColor"}, + {aiTextureType_DIFFUSE, "DiffuseColor"}, + {aiTextureType_SPECULAR, "SpecularColor"}, + {aiTextureType_AMBIENT, "AmbientColor"}, + {aiTextureType_EMISSIVE, "EmissiveColor"}, + {aiTextureType_HEIGHT, "Bump"}, + {aiTextureType_NORMALS, "NormalMap"}, + {aiTextureType_SHININESS, "ShininessExponent"}, + {aiTextureType_OPACITY, "TransparentColor"}, {aiTextureType_DISPLACEMENT, "DisplacementColor"}, //{aiTextureType_LIGHTMAP, "???"}, - {aiTextureType_REFLECTION, "ReflectionColor"} + {aiTextureType_REFLECTION, "ReflectionColor"} //{aiTextureType_UNKNOWN, ""} }; for (size_t i = 0; i < mScene->mNumMaterials; ++i) { @@ -1573,19 +1676,41 @@ void FBXExporter::WriteObjects () // one sticky point is that the number of vertices may not match, // because assimp splits vertices by normal, uv, etc. + // functor for aiNode sorting + struct SortNodeByName + { + bool operator()(const aiNode *lhs, const aiNode *rhs) const + { + return strcmp(lhs->mName.C_Str(), rhs->mName.C_Str()) < 0; + } + }; + // first we should mark the skeleton for each mesh. // the skeleton must include not only the aiBones, // but also all their parent nodes. // anything that affects the position of any bone node must be included. - std::vector> skeleton_by_mesh(mScene->mNumMeshes); + // Use SorNodeByName to make sure the exported result will be the same across all systems + // Otherwise the aiNodes of the skeleton would be sorted based on the pointer address, which isn't consistent + std::vector> skeleton_by_mesh(mScene->mNumMeshes); // at the same time we can build a list of all the skeleton nodes, // which will be used later to mark them as type "limbNode". std::unordered_set limbnodes; + + //actual bone nodes in fbx, without parenting-up + std::unordered_set setAllBoneNamesInScene; + for(unsigned int m = 0; m < mScene->mNumMeshes; ++ m) + { + aiMesh* pMesh = mScene->mMeshes[m]; + for(unsigned int b = 0; b < pMesh->mNumBones; ++ b) + setAllBoneNamesInScene.insert(pMesh->mBones[b]->mName.data); + } + aiMatrix4x4 mxTransIdentity; + // and a map of nodes by bone name, as finding them is annoying. std::map node_by_bone; for (size_t mi = 0; mi < mScene->mNumMeshes; ++mi) { const aiMesh* m = mScene->mMeshes[mi]; - std::set skeleton; + std::set skeleton; for (size_t bi =0; bi < m->mNumBones; ++bi) { const aiBone* b = m->mBones[bi]; const std::string name(b->mName.C_Str()); @@ -1624,6 +1749,11 @@ void FBXExporter::WriteObjects () if (node_name.find(MAGIC_NODE_TAG) != std::string::npos) { continue; } + //not a bone in scene && no effect in transform + if(setAllBoneNamesInScene.find(node_name)==setAllBoneNamesInScene.end() + && parent->mTransformation == mxTransIdentity) { + continue; + } // otherwise check if this is the root of the skeleton bool end = false; // is the mesh part of this node? @@ -1644,8 +1774,7 @@ void FBXExporter::WriteObjects () } if (end) { break; } } - limbnodes.insert(parent); - skeleton.insert(parent); + // if it was the skeleton root we can finish here if (end) { break; } } @@ -1687,28 +1816,8 @@ void FBXExporter::WriteObjects () // connect it connections.emplace_back("C", "OO", deformer_uid, mesh_uids[mi]); - // we will be indexing by vertex... - // but there might be a different number of "vertices" - // between assimp and our output FBX. - // this code is cut-and-pasted from the geometry section above... - // ideally this should not be so. - // --- - // index of original vertex in vertex data vector - std::vector vertex_indices; - // map of vertex value to its index in the data vector - std::map index_by_vertex_value; - int32_t index = 0; - for (size_t vi = 0; vi < m->mNumVertices; ++vi) { - aiVector3D vtx = m->mVertices[vi]; - auto elem = index_by_vertex_value.find(vtx); - if (elem == index_by_vertex_value.end()) { - vertex_indices.push_back(index); - index_by_vertex_value[vtx] = index; - ++index; - } else { - vertex_indices.push_back(int32_t(elem->second)); - } - } + //computed before + std::vector& vertex_indices = vVertexIndice[mi]; // TODO, FIXME: this won't work if anything is not in the bind pose. // for now if such a situation is detected, we throw an exception. @@ -1726,7 +1835,7 @@ void FBXExporter::WriteObjects () aiMatrix4x4 mesh_xform = get_world_transform(mesh_node, mScene); // now make a subdeformer for each bone in the skeleton - const std::set &skeleton = skeleton_by_mesh[mi]; + const std::set skeleton= skeleton_by_mesh[mi]; for (const aiNode* bone_node : skeleton) { // if there's a bone for this node, find it const aiBone* b = nullptr; @@ -1786,41 +1895,10 @@ void FBXExporter::WriteObjects () inverse_bone_xform.Inverse(); aiMatrix4x4 tr = inverse_bone_xform * mesh_xform; - // this should be the same as the bone's mOffsetMatrix. - // if it's not the same, the skeleton isn't in the bind pose. - const float epsilon = 1e-4f; // some error is to be expected - bool bone_xform_okay = true; - if (b && ! tr.Equal(b->mOffsetMatrix, epsilon)) { - not_in_bind_pose.insert(b); - bone_xform_okay = false; - } + sdnode.AddChild("Transform", tr); - // if we have a bone we should use the mOffsetMatrix, - // otherwise try to just use the calculated transform. - if (b) { - sdnode.AddChild("Transform", b->mOffsetMatrix); - } else { - sdnode.AddChild("Transform", tr); - } - // note: it doesn't matter if we mix these, - // because if they disagree we'll throw an exception later. - // it could be that the skeleton is not in the bone pose - // but all bones are still defined, - // in which case this would use the mOffsetMatrix for everything - // and a correct skeleton would still be output. - // transformlink should be the position of the bone in world space. - // if the bone is in the bind pose (or nonexistent), - // we can just use the matrix we already calculated - if (bone_xform_okay) { - sdnode.AddChild("TransformLink", bone_xform); - // otherwise we can only work it out using the mesh position. - } else { - aiMatrix4x4 trl = b->mOffsetMatrix; - trl.Inverse(); - trl *= mesh_xform; - sdnode.AddChild("TransformLink", trl); - } + sdnode.AddChild("TransformLink", bone_xform); // note: this means we ALWAYS rely on the mesh node transform // being unchanged from the time the skeleton was bound. // there's not really any way around this at the moment. @@ -2235,8 +2313,8 @@ void FBXExporter::WriteModelNode( // not sure what these are for, // but they seem to be omnipresent - m.AddChild("Shading", Property(true)); - m.AddChild("Culling", Property("CullingOff")); + m.AddChild("Shading", FBXExportProperty(true)); + m.AddChild("Culling", FBXExportProperty("CullingOff")); m.Dump(outstream, binary, 1); } @@ -2349,7 +2427,7 @@ void FBXExporter::WriteModelNodes( na.AddProperties( node_attribute_uid, FBX::SEPARATOR + "NodeAttribute", "LimbNode" ); - na.AddChild("TypeFlags", Property("Skeleton")); + na.AddChild("TypeFlags", FBXExportProperty("Skeleton")); na.Dump(outstream, binary, 1); // and connect them connections.emplace_back("C", "OO", node_attribute_uid, node_uid); @@ -2405,7 +2483,7 @@ void FBXExporter::WriteModelNodes( void FBXExporter::WriteAnimationCurveNode( StreamWriterLE& outstream, int64_t uid, - std::string name, // "T", "R", or "S" + const std::string& name, // "T", "R", or "S" aiVector3D default_value, std::string property_name, // "Lcl Translation" etc int64_t layer_uid, @@ -2444,7 +2522,6 @@ void FBXExporter::WriteAnimationCurve( // TODO: keyattr flags and data (STUB for now) n.AddChild("KeyAttrFlags", std::vector{0}); n.AddChild("KeyAttrDataFloat", std::vector{0,0,0,0}); - ai_assert(static_cast(times.size()) <= std::numeric_limits::max()); n.AddChild( "KeyAttrRefCount", std::vector{static_cast(times.size())} diff --git a/third_party/libassimp/code/FBXExporter.h b/third_party/libassimp/code/FBX/FBXExporter.h similarity index 98% rename from third_party/libassimp/code/FBXExporter.h rename to third_party/libassimp/code/FBX/FBXExporter.h index c27d1a8ce1..1ae727eda9 100644 --- a/third_party/libassimp/code/FBXExporter.h +++ b/third_party/libassimp/code/FBX/FBXExporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -156,7 +156,7 @@ namespace Assimp void WriteAnimationCurveNode( StreamWriterLE& outstream, int64_t uid, - std::string name, // "T", "R", or "S" + const std::string& name, // "T", "R", or "S" aiVector3D default_value, std::string property_name, // "Lcl Translation" etc int64_t animation_layer_uid, diff --git a/third_party/libassimp/code/FBXImportSettings.h b/third_party/libassimp/code/FBX/FBXImportSettings.h similarity index 87% rename from third_party/libassimp/code/FBXImportSettings.h rename to third_party/libassimp/code/FBX/FBXImportSettings.h index e612fddefa..1a4c80f8b2 100644 --- a/third_party/libassimp/code/FBXImportSettings.h +++ b/third_party/libassimp/code/FBX/FBXImportSettings.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -53,19 +53,22 @@ namespace FBX { struct ImportSettings { ImportSettings() - : strictMode(true) - , readAllLayers(true) - , readAllMaterials(false) - , readMaterials(true) - , readTextures(true) - , readCameras(true) - , readLights(true) - , readAnimations(true) - , readWeights(true) - , preservePivots(true) - , optimizeEmptyAnimationCurves(true) - , useLegacyEmbeddedTextureNaming(false) - {} + : strictMode(true) + , readAllLayers(true) + , readAllMaterials(false) + , readMaterials(true) + , readTextures(true) + , readCameras(true) + , readLights(true) + , readAnimations(true) + , readWeights(true) + , preservePivots(true) + , optimizeEmptyAnimationCurves(true) + , useLegacyEmbeddedTextureNaming(false) + , removeEmptyBones( true ) + , convertToMeters( false ) { + // empty + } /** enable strict mode: @@ -141,8 +144,16 @@ struct ImportSettings bool optimizeEmptyAnimationCurves; /** use legacy naming for embedded textures eg: (*0, *1, *2) - **/ + */ bool useLegacyEmbeddedTextureNaming; + + /** Empty bones shall be removed + */ + bool removeEmptyBones; + + /** Set to true to perform a conversion from cm to meter after the import + */ + bool convertToMeters; }; diff --git a/third_party/libassimp/code/FBXImporter.cpp b/third_party/libassimp/code/FBX/FBXImporter.cpp similarity index 90% rename from third_party/libassimp/code/FBXImporter.cpp rename to third_party/libassimp/code/FBX/FBXImporter.cpp index b004bcd8cb..c8c1a6853d 100644 --- a/third_party/libassimp/code/FBXImporter.cpp +++ b/third_party/libassimp/code/FBX/FBXImporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -60,11 +60,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include namespace Assimp { - template<> const char* LogFunctions::Prefix() - { - static auto prefix = "FBX: "; - return prefix; - } + +template<> +const char* LogFunctions::Prefix() { + static auto prefix = "FBX: "; + return prefix; +} + } using namespace Assimp; @@ -72,6 +74,7 @@ using namespace Assimp::Formatter; using namespace Assimp::FBX; namespace { + static const aiImporterDesc desc = { "Autodesk FBX Importer", "", @@ -137,6 +140,8 @@ void FBXImporter::SetupProperties(const Importer* pImp) settings.preservePivots = pImp->GetPropertyBool(AI_CONFIG_IMPORT_FBX_PRESERVE_PIVOTS, true); settings.optimizeEmptyAnimationCurves = pImp->GetPropertyBool(AI_CONFIG_IMPORT_FBX_OPTIMIZE_EMPTY_ANIMATION_CURVES, true); settings.useLegacyEmbeddedTextureNaming = pImp->GetPropertyBool(AI_CONFIG_IMPORT_FBX_EMBEDDED_TEXTURES_LEGACY_NAMING, false); + settings.removeEmptyBones = pImp->GetPropertyBool(AI_CONFIG_IMPORT_REMOVE_EMPTY_BONES, true); + settings.convertToMeters = pImp->GetPropertyBool(AI_CONFIG_FBX_CONVERT_TO_M, false); } // ------------------------------------------------------------------------------------------------ @@ -167,7 +172,7 @@ void FBXImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOS bool is_binary = false; if (!strncmp(begin,"Kaydara FBX Binary",18)) { is_binary = true; - TokenizeBinary(tokens,begin,static_cast(contents.size())); + TokenizeBinary(tokens,begin,contents.size()); } else { Tokenize(tokens,begin); @@ -181,7 +186,14 @@ void FBXImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOS Document doc(parser,settings); // convert the FBX DOM to aiScene - ConvertToAssimpScene(pScene,doc); + ConvertToAssimpScene(pScene, doc, settings.removeEmptyBones); + + // size relative to cm + float size_relative_to_cm = doc.GlobalSettings().UnitScaleFactor(); + + // Set FBX file scale is relative to CM must be converted to M for + // assimp universal format (M) + SetFileScale( size_relative_to_cm * 0.01f); std::for_each(tokens.begin(),tokens.end(),Util::delete_fun()); } diff --git a/third_party/libassimp/code/FBXImporter.h b/third_party/libassimp/code/FBX/FBXImporter.h similarity index 98% rename from third_party/libassimp/code/FBXImporter.h rename to third_party/libassimp/code/FBX/FBXImporter.h index 870f1c49bd..c365b2cddf 100644 --- a/third_party/libassimp/code/FBXImporter.h +++ b/third_party/libassimp/code/FBX/FBXImporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/FBXMaterial.cpp b/third_party/libassimp/code/FBX/FBXMaterial.cpp similarity index 78% rename from third_party/libassimp/code/FBXMaterial.cpp rename to third_party/libassimp/code/FBX/FBXMaterial.cpp index 75b2e3b4ba..f43a8b84b0 100644 --- a/third_party/libassimp/code/FBXMaterial.cpp +++ b/third_party/libassimp/code/FBX/FBXMaterial.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -55,6 +55,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include // std::transform +#include "FBXUtil.h" namespace Assimp { namespace FBX { @@ -206,6 +207,20 @@ Texture::Texture(uint64_t id, const Element& element, const Document& doc, const props = GetPropertyTable(doc,"Texture.FbxFileTexture",element,sc); + // 3DS Max and FBX SDK use "Scaling" and "Translation" instead of "ModelUVScaling" and "ModelUVTranslation". Use these properties if available. + bool ok; + const aiVector3D& scaling = PropertyGet(*props, "Scaling", ok); + if (ok) { + uvScaling.x = scaling.x; + uvScaling.y = scaling.y; + } + + const aiVector3D& trans = PropertyGet(*props, "Translation", ok); + if (ok) { + uvTrans.x = trans.x; + uvTrans.y = trans.y; + } + // resolve video links if(doc.Settings().readTextures) { const std::vector& conns = doc.GetConnectionsByDestinationSequenced(ID()); @@ -301,13 +316,52 @@ Video::Video(uint64_t id, const Element& element, const Document& doc, const std relativeFileName = ParseTokenAsString(GetRequiredToken(*RelativeFilename,0)); } - if(Content) { + if(Content && !Content->Tokens().empty()) { //this field is omitted when the embedded texture is already loaded, let's ignore if it's not found try { const Token& token = GetRequiredToken(*Content, 0); const char* data = token.begin(); if (!token.IsBinary()) { - DOMWarning("video content is not binary data, ignoring", &element); + if (*data != '"') { + DOMError("embedded content is not surrounded by quotation marks", &element); + } + else { + size_t targetLength = 0; + auto numTokens = Content->Tokens().size(); + // First time compute size (it could be large like 64Gb and it is good to allocate it once) + for (uint32_t tokenIdx = 0; tokenIdx < numTokens; ++tokenIdx) + { + const Token& dataToken = GetRequiredToken(*Content, tokenIdx); + size_t tokenLength = dataToken.end() - dataToken.begin() - 2; // ignore double quotes + const char* base64data = dataToken.begin() + 1; + const size_t outLength = Util::ComputeDecodedSizeBase64(base64data, tokenLength); + if (outLength == 0) + { + DOMError("Corrupted embedded content found", &element); + } + targetLength += outLength; + } + if (targetLength == 0) + { + DOMError("Corrupted embedded content found", &element); + } + content = new uint8_t[targetLength]; + contentLength = static_cast(targetLength); + size_t dst_offset = 0; + for (uint32_t tokenIdx = 0; tokenIdx < numTokens; ++tokenIdx) + { + const Token& dataToken = GetRequiredToken(*Content, tokenIdx); + size_t tokenLength = dataToken.end() - dataToken.begin() - 2; // ignore double quotes + const char* base64data = dataToken.begin() + 1; + dst_offset += Util::DecodeBase64(base64data, tokenLength, content + dst_offset, targetLength - dst_offset); + } + if (targetLength != dst_offset) + { + delete[] content; + contentLength = 0; + DOMError("Corrupted embedded content found", &element); + } + } } else if (static_cast(token.end() - data) < 5) { DOMError("binary data array is too short, need five (5) bytes for type signature and element count", &element); @@ -326,8 +380,11 @@ Video::Video(uint64_t id, const Element& element, const Document& doc, const std content = new uint8_t[len]; ::memcpy(content, data + 5, len); } - } catch (runtime_error runtimeError) { + } catch (const runtime_error& runtimeError) + { //we don't need the content data for contents that has already been loaded + ASSIMP_LOG_DEBUG_F("Caught exception in FBXMaterial (likely because content was already loaded): ", + runtimeError.what()); } } diff --git a/third_party/libassimp/code/FBXMeshGeometry.cpp b/third_party/libassimp/code/FBX/FBXMeshGeometry.cpp similarity index 86% rename from third_party/libassimp/code/FBXMeshGeometry.cpp rename to third_party/libassimp/code/FBX/FBXMeshGeometry.cpp index aa794d4df1..1386e2383c 100644 --- a/third_party/libassimp/code/FBXMeshGeometry.cpp +++ b/third_party/libassimp/code/FBX/FBXMeshGeometry.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -62,7 +62,7 @@ using namespace Util; // ------------------------------------------------------------------------------------------------ Geometry::Geometry(uint64_t id, const Element& element, const std::string& name, const Document& doc) - : Object(id, element,name) + : Object(id, element, name) , skin() { const std::vector& conns = doc.GetConnectionsByDestinationSequenced(ID(),"Deformer"); @@ -70,18 +70,26 @@ Geometry::Geometry(uint64_t id, const Element& element, const std::string& name, const Skin* const sk = ProcessSimpleConnection(*con, false, "Skin -> Geometry", element); if(sk) { skin = sk; - break; + } + const BlendShape* const bsp = ProcessSimpleConnection(*con, false, "BlendShape -> Geometry", element); + if (bsp) { + blendShapes.push_back(bsp); } } } - // ------------------------------------------------------------------------------------------------ Geometry::~Geometry() { // empty } +// ------------------------------------------------------------------------------------------------ +const std::vector& Geometry::GetBlendShapes() const { + return blendShapes; +} + +// ------------------------------------------------------------------------------------------------ const Skin* Geometry::DeformerSkin() const { return skin; } @@ -107,7 +115,6 @@ MeshGeometry::MeshGeometry(uint64_t id, const Element& element, const std::strin if(tempVerts.empty()) { FBXImporter::LogWarn("encountered mesh with no vertices"); - return; } std::vector tempFaces; @@ -115,7 +122,6 @@ MeshGeometry::MeshGeometry(uint64_t id, const Element& element, const std::strin if(tempFaces.empty()) { FBXImporter::LogWarn("encountered mesh with no faces"); - return; } m_vertices.reserve(tempFaces.size()); @@ -232,7 +238,6 @@ const std::vector& MeshGeometry::GetVertexColors( unsigned int index const MatIndexArray& MeshGeometry::GetMaterialIndices() const { return m_materials; } - // ------------------------------------------------------------------------------------------------ const unsigned int* MeshGeometry::ToOutputVertexIndex( unsigned int in_index, unsigned int& count ) const { if ( in_index >= m_mapping_counts.size() ) { @@ -561,15 +566,15 @@ void MeshGeometry::ReadVertexDataColors(std::vector& colors_out, cons } // ------------------------------------------------------------------------------------------------ -static const std::string TangentIndexToken = "TangentIndex"; -static const std::string TangentsIndexToken = "TangentsIndex"; +static const char *TangentIndexToken = "TangentIndex"; +static const char *TangentsIndexToken = "TangentsIndex"; void MeshGeometry::ReadVertexDataTangents(std::vector& tangents_out, const Scope& source, const std::string& MappingInformationType, const std::string& ReferenceInformationType) { const char * str = source.Elements().count( "Tangents" ) > 0 ? "Tangents" : "Tangent"; - const char * strIdx = source.Elements().count( "Tangents" ) > 0 ? TangentsIndexToken.c_str() : TangentIndexToken.c_str(); + const char * strIdx = source.Elements().count( "Tangents" ) > 0 ? TangentsIndexToken : TangentIndexToken; ResolveVertexDataArray(tangents_out,source,MappingInformationType,ReferenceInformationType, str, strIdx, @@ -605,8 +610,11 @@ void MeshGeometry::ReadVertexDataMaterials(std::vector& materials_out, cons const std::string& ReferenceInformationType) { const size_t face_count = m_faces.size(); - ai_assert(face_count); - + if( 0 == face_count ) + { + return; + } + // materials are handled separately. First of all, they are assigned per-face // and not per polyvert. Secondly, ReferenceInformationType=IndexToDirect // has a slightly different meaning for materials. @@ -617,16 +625,15 @@ void MeshGeometry::ReadVertexDataMaterials(std::vector& materials_out, cons if (materials_out.empty()) { FBXImporter::LogError(Formatter::format("expected material index, ignoring")); return; - } - else if (materials_out.size() > 1) { + } else if (materials_out.size() > 1) { FBXImporter::LogWarn(Formatter::format("expected only a single material index, ignoring all except the first one")); materials_out.clear(); } - m_materials.assign(m_vertices.size(),materials_out[0]); - } - else if (MappingInformationType == "ByPolygon" && ReferenceInformationType == "IndexToDirect") { - m_materials.resize(face_count); + materials_out.resize(m_vertices.size()); + std::fill(materials_out.begin(), materials_out.end(), materials_out.at(0)); + } else if (MappingInformationType == "ByPolygon" && ReferenceInformationType == "IndexToDirect") { + materials_out.resize(face_count); if(materials_out.size() != face_count) { FBXImporter::LogError(Formatter::format("length of input data unexpected for ByPolygon mapping: ") @@ -634,15 +641,69 @@ void MeshGeometry::ReadVertexDataMaterials(std::vector& materials_out, cons ); return; } - } - else { + } else { FBXImporter::LogError(Formatter::format("ignoring material assignments, access type not implemented: ") << MappingInformationType << "," << ReferenceInformationType); } } +// ------------------------------------------------------------------------------------------------ +ShapeGeometry::ShapeGeometry(uint64_t id, const Element& element, const std::string& name, const Document& doc) +: Geometry(id, element, name, doc) { + const Scope *sc = element.Compound(); + if (nullptr == sc) { + DOMError("failed to read Geometry object (class: Shape), no data scope found"); + } + const Element& Indexes = GetRequiredElement(*sc, "Indexes", &element); + const Element& Normals = GetRequiredElement(*sc, "Normals", &element); + const Element& Vertices = GetRequiredElement(*sc, "Vertices", &element); + ParseVectorDataArray(m_indices, Indexes); + ParseVectorDataArray(m_vertices, Vertices); + ParseVectorDataArray(m_normals, Normals); +} +// ------------------------------------------------------------------------------------------------ +ShapeGeometry::~ShapeGeometry() { + // empty +} +// ------------------------------------------------------------------------------------------------ +const std::vector& ShapeGeometry::GetVertices() const { + return m_vertices; +} +// ------------------------------------------------------------------------------------------------ +const std::vector& ShapeGeometry::GetNormals() const { + return m_normals; +} +// ------------------------------------------------------------------------------------------------ +const std::vector& ShapeGeometry::GetIndices() const { + return m_indices; +} +// ------------------------------------------------------------------------------------------------ +LineGeometry::LineGeometry(uint64_t id, const Element& element, const std::string& name, const Document& doc) + : Geometry(id, element, name, doc) +{ + const Scope* sc = element.Compound(); + if (!sc) { + DOMError("failed to read Geometry object (class: Line), no data scope found"); + } + const Element& Points = GetRequiredElement(*sc, "Points", &element); + const Element& PointsIndex = GetRequiredElement(*sc, "PointsIndex", &element); + ParseVectorDataArray(m_vertices, Points); + ParseVectorDataArray(m_indices, PointsIndex); +} + +// ------------------------------------------------------------------------------------------------ +LineGeometry::~LineGeometry() { + // empty +} +// ------------------------------------------------------------------------------------------------ +const std::vector& LineGeometry::GetVertices() const { + return m_vertices; +} +// ------------------------------------------------------------------------------------------------ +const std::vector& LineGeometry::GetIndices() const { + return m_indices; +} } // !FBX } // !Assimp - #endif diff --git a/third_party/libassimp/code/FBXMeshGeometry.h b/third_party/libassimp/code/FBX/FBXMeshGeometry.h similarity index 80% rename from third_party/libassimp/code/FBXMeshGeometry.h rename to third_party/libassimp/code/FBX/FBXMeshGeometry.h index acd44668a4..d6d4512177 100644 --- a/third_party/libassimp/code/FBXMeshGeometry.h +++ b/third_party/libassimp/code/FBX/FBXMeshGeometry.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -64,8 +64,13 @@ public: /** Get the Skin attached to this geometry or NULL */ const Skin* DeformerSkin() const; + /** Get the BlendShape attached to this geometry or NULL */ + const std::vector& GetBlendShapes() const; + private: const Skin* skin; + std::vector blendShapes; + }; typedef std::vector MatIndexArray; @@ -125,7 +130,6 @@ public: /** Determine the face to which a particular output vertex index belongs. * This mapping is always unique. */ unsigned int FaceForVertexIndex( unsigned int in_index ) const; - private: void ReadLayer( const Scope& layer ); void ReadLayerElement( const Scope& layerElement ); @@ -174,6 +178,56 @@ private: std::vector m_mappings; }; +/** +* DOM class for FBX geometry of type "Shape" +*/ +class ShapeGeometry : public Geometry +{ +public: + /** The class constructor */ + ShapeGeometry(uint64_t id, const Element& element, const std::string& name, const Document& doc); + + /** The class destructor */ + virtual ~ShapeGeometry(); + + /** Get a list of all vertex points, non-unique*/ + const std::vector& GetVertices() const; + + /** Get a list of all vertex normals or an empty array if + * no normals are specified. */ + const std::vector& GetNormals() const; + + /** Return list of vertex indices. */ + const std::vector& GetIndices() const; + +private: + std::vector m_vertices; + std::vector m_normals; + std::vector m_indices; +}; +/** +* DOM class for FBX geometry of type "Line" +*/ +class LineGeometry : public Geometry +{ +public: + /** The class constructor */ + LineGeometry(uint64_t id, const Element& element, const std::string& name, const Document& doc); + + /** The class destructor */ + virtual ~LineGeometry(); + + /** Get a list of all vertex points, non-unique*/ + const std::vector& GetVertices() const; + + /** Return list of vertex indices. */ + const std::vector& GetIndices() const; + +private: + std::vector m_vertices; + std::vector m_indices; +}; + } } diff --git a/third_party/libassimp/code/FBXModel.cpp b/third_party/libassimp/code/FBX/FBXModel.cpp similarity index 99% rename from third_party/libassimp/code/FBXModel.cpp rename to third_party/libassimp/code/FBX/FBXModel.cpp index c16ca841cd..589af36ac7 100644 --- a/third_party/libassimp/code/FBXModel.cpp +++ b/third_party/libassimp/code/FBX/FBXModel.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/FBXNodeAttribute.cpp b/third_party/libassimp/code/FBX/FBXNodeAttribute.cpp similarity index 99% rename from third_party/libassimp/code/FBXNodeAttribute.cpp rename to third_party/libassimp/code/FBX/FBXNodeAttribute.cpp index 1064151b3a..b72e5637ee 100644 --- a/third_party/libassimp/code/FBXNodeAttribute.cpp +++ b/third_party/libassimp/code/FBX/FBXNodeAttribute.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/FBXParser.cpp b/third_party/libassimp/code/FBX/FBXParser.cpp similarity index 99% rename from third_party/libassimp/code/FBXParser.cpp rename to third_party/libassimp/code/FBX/FBXParser.cpp index 96d113bd1d..4a9346040d 100644 --- a/third_party/libassimp/code/FBXParser.cpp +++ b/third_party/libassimp/code/FBX/FBXParser.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -117,7 +117,7 @@ namespace FBX { Element::Element(const Token& key_token, Parser& parser) : key_token(key_token) { - TokenPtr n = NULL; + TokenPtr n = nullptr; do { n = parser.AdvanceToNextToken(); if(!n) { @@ -643,9 +643,9 @@ void ParseVectorDataArray(std::vector& out, const Element& el) if (type == 'd') { const double* d = reinterpret_cast(&buff[0]); for (unsigned int i = 0; i < count3; ++i, d += 3) { - out.push_back(aiVector3D(static_cast(d[0]), - static_cast(d[1]), - static_cast(d[2]))); + out.push_back(aiVector3D(static_cast(d[0]), + static_cast(d[1]), + static_cast(d[2]))); } // for debugging /*for ( size_t i = 0; i < out.size(); i++ ) { @@ -963,7 +963,6 @@ void ParseVectorDataArray(std::vector& out, const Element& el) } } - // ------------------------------------------------------------------------------------------------ // read an array of uints void ParseVectorDataArray(std::vector& out, const Element& el) @@ -1280,7 +1279,6 @@ float ParseTokenAsFloat(const Token& t) return i; } - // ------------------------------------------------------------------------------------------------ // wrapper around ParseTokenAsInt() with ParseError handling int ParseTokenAsInt(const Token& t) @@ -1293,8 +1291,6 @@ int ParseTokenAsInt(const Token& t) return i; } - - // ------------------------------------------------------------------------------------------------ // wrapper around ParseTokenAsInt64() with ParseError handling int64_t ParseTokenAsInt64(const Token& t) diff --git a/third_party/libassimp/code/FBXParser.h b/third_party/libassimp/code/FBX/FBXParser.h similarity index 99% rename from third_party/libassimp/code/FBXParser.h rename to third_party/libassimp/code/FBX/FBXParser.h index 389da3fed1..7b0cf72039 100644 --- a/third_party/libassimp/code/FBXParser.h +++ b/third_party/libassimp/code/FBX/FBXParser.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/FBXProperties.cpp b/third_party/libassimp/code/FBX/FBXProperties.cpp similarity index 99% rename from third_party/libassimp/code/FBXProperties.cpp rename to third_party/libassimp/code/FBX/FBXProperties.cpp index ca89743cab..8d7036b6a9 100644 --- a/third_party/libassimp/code/FBXProperties.cpp +++ b/third_party/libassimp/code/FBX/FBXProperties.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/FBXProperties.h b/third_party/libassimp/code/FBX/FBXProperties.h similarity index 99% rename from third_party/libassimp/code/FBXProperties.h rename to third_party/libassimp/code/FBX/FBXProperties.h index 404e04debc..58755542fc 100644 --- a/third_party/libassimp/code/FBXProperties.h +++ b/third_party/libassimp/code/FBX/FBXProperties.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/FBXTokenizer.cpp b/third_party/libassimp/code/FBX/FBXTokenizer.cpp similarity index 99% rename from third_party/libassimp/code/FBXTokenizer.cpp rename to third_party/libassimp/code/FBX/FBXTokenizer.cpp index c9dd1697a5..252cce3557 100644 --- a/third_party/libassimp/code/FBXTokenizer.cpp +++ b/third_party/libassimp/code/FBX/FBXTokenizer.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/FBXTokenizer.h b/third_party/libassimp/code/FBX/FBXTokenizer.h similarity index 96% rename from third_party/libassimp/code/FBXTokenizer.h rename to third_party/libassimp/code/FBX/FBXTokenizer.h index e939826176..afa588a470 100644 --- a/third_party/libassimp/code/FBXTokenizer.h +++ b/third_party/libassimp/code/FBX/FBXTokenizer.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -93,7 +93,7 @@ public: Token(const char* sbegin, const char* send, TokenType type, unsigned int line, unsigned int column); /** construct a binary token */ - Token(const char* sbegin, const char* send, TokenType type, unsigned int offset); + Token(const char* sbegin, const char* send, TokenType type, size_t offset); ~Token(); @@ -118,14 +118,14 @@ public: return type; } - unsigned int Offset() const { + size_t Offset() const { ai_assert(IsBinary()); return offset; } unsigned int Line() const { ai_assert(!IsBinary()); - return line; + return static_cast(line); } unsigned int Column() const { @@ -147,8 +147,8 @@ private: const TokenType type; union { - const unsigned int line; - unsigned int offset; + size_t line; + size_t offset; }; const unsigned int column; }; @@ -178,7 +178,7 @@ void Tokenize(TokenList& output_tokens, const char* input); * @param input_buffer Binary input buffer to be processed. * @param length Length of input buffer, in bytes. There is no 0-terminal. * @throw DeadlyImportError if something goes wrong */ -void TokenizeBinary(TokenList& output_tokens, const char* input, unsigned int length); +void TokenizeBinary(TokenList& output_tokens, const char* input, size_t length); } // ! FBX diff --git a/third_party/libassimp/code/FBX/FBXUtil.cpp b/third_party/libassimp/code/FBX/FBXUtil.cpp new file mode 100644 index 0000000000..c10e057c8c --- /dev/null +++ b/third_party/libassimp/code/FBX/FBXUtil.cpp @@ -0,0 +1,243 @@ +/* +Open Asset Import Library (assimp) +---------------------------------------------------------------------- + +Copyright (c) 2006-2019, 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 FBXUtil.cpp + * @brief Implementation of internal FBX utility functions + */ + +#include "FBXUtil.h" +#include "FBXTokenizer.h" + +#include +#include +#include + +#ifndef ASSIMP_BUILD_NO_FBX_IMPORTER + +namespace Assimp { +namespace FBX { +namespace Util { + +// ------------------------------------------------------------------------------------------------ +const char* TokenTypeString(TokenType t) +{ + switch(t) { + case TokenType_OPEN_BRACKET: + return "TOK_OPEN_BRACKET"; + + case TokenType_CLOSE_BRACKET: + return "TOK_CLOSE_BRACKET"; + + case TokenType_DATA: + return "TOK_DATA"; + + case TokenType_COMMA: + return "TOK_COMMA"; + + case TokenType_KEY: + return "TOK_KEY"; + + case TokenType_BINARY_DATA: + return "TOK_BINARY_DATA"; + } + + ai_assert(false); + return ""; +} + + +// ------------------------------------------------------------------------------------------------ +std::string AddOffset(const std::string& prefix, const std::string& text, size_t offset) +{ + return static_cast( (Formatter::format() << prefix << " (offset 0x" << std::hex << offset << ") " << text) ); +} + +// ------------------------------------------------------------------------------------------------ +std::string AddLineAndColumn(const std::string& prefix, const std::string& text, unsigned int line, unsigned int column) +{ + return static_cast( (Formatter::format() << prefix << " (line " << line << " << col " << column << ") " << text) ); +} + +// ------------------------------------------------------------------------------------------------ +std::string AddTokenText(const std::string& prefix, const std::string& text, const Token* tok) +{ + if(tok->IsBinary()) { + return static_cast( (Formatter::format() << prefix << + " (" << TokenTypeString(tok->Type()) << + ", offset 0x" << std::hex << tok->Offset() << ") " << + text) ); + } + + return static_cast( (Formatter::format() << prefix << + " (" << TokenTypeString(tok->Type()) << + ", line " << tok->Line() << + ", col " << tok->Column() << ") " << + text) ); +} + +// Generated by this formula: T["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[i]] = i; +static const uint8_t base64DecodeTable[128] = { + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 255, 255, 255, + 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255, + 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 255, 255, 255, 255, 255 +}; + +uint8_t DecodeBase64(char ch) +{ + const auto idx = static_cast(ch); + if (idx > 127) + return 255; + return base64DecodeTable[idx]; +} + +size_t ComputeDecodedSizeBase64(const char* in, size_t inLength) +{ + if (inLength < 2) + { + return 0; + } + const size_t equals = size_t(in[inLength - 1] == '=') + size_t(in[inLength - 2] == '='); + const size_t full_length = (inLength * 3) >> 2; // div by 4 + if (full_length < equals) + { + return 0; + } + return full_length - equals; +} + +size_t DecodeBase64(const char* in, size_t inLength, uint8_t* out, size_t maxOutLength) +{ + if (maxOutLength == 0 || inLength < 2) { + return 0; + } + const size_t realLength = inLength - size_t(in[inLength - 1] == '=') - size_t(in[inLength - 2] == '='); + size_t dst_offset = 0; + int val = 0, valb = -8; + for (size_t src_offset = 0; src_offset < realLength; ++src_offset) + { + const uint8_t table_value = Util::DecodeBase64(in[src_offset]); + if (table_value == 255) + { + return 0; + } + val = (val << 6) + table_value; + valb += 6; + if (valb >= 0) + { + out[dst_offset++] = static_cast((val >> valb) & 0xFF); + valb -= 8; + val &= 0xFFF; + } + } + return dst_offset; +} + +static const char to_base64_string[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +char EncodeBase64(char byte) +{ + return to_base64_string[(size_t)byte]; +} + +/** Encodes a block of 4 bytes to base64 encoding +* +* @param bytes Bytes to encode. +* @param out_string String to write encoded values to. +* @param string_pos Position in out_string.*/ +void EncodeByteBlock(const char* bytes, std::string& out_string, size_t string_pos) +{ + char b0 = (bytes[0] & 0xFC) >> 2; + char b1 = (bytes[0] & 0x03) << 4 | ((bytes[1] & 0xF0) >> 4); + char b2 = (bytes[1] & 0x0F) << 2 | ((bytes[2] & 0xC0) >> 6); + char b3 = (bytes[2] & 0x3F); + + out_string[string_pos + 0] = EncodeBase64(b0); + out_string[string_pos + 1] = EncodeBase64(b1); + out_string[string_pos + 2] = EncodeBase64(b2); + out_string[string_pos + 3] = EncodeBase64(b3); +} + +std::string EncodeBase64(const char* data, size_t length) +{ + // calculate extra bytes needed to get a multiple of 3 + size_t extraBytes = 3 - length % 3; + + // number of base64 bytes + size_t encodedBytes = 4 * (length + extraBytes) / 3; + + std::string encoded_string(encodedBytes, '='); + + // read blocks of 3 bytes + for (size_t ib3 = 0; ib3 < length / 3; ib3++) + { + const size_t iByte = ib3 * 3; + const size_t iEncodedByte = ib3 * 4; + const char* currData = &data[iByte]; + + EncodeByteBlock(currData, encoded_string, iEncodedByte); + } + + // if size of data is not a multiple of 3, also encode the final bytes (and add zeros where needed) + if (extraBytes > 0) + { + char finalBytes[4] = { 0,0,0,0 }; + memcpy(&finalBytes[0], &data[length - length % 3], length % 3); + + const size_t iEncodedByte = encodedBytes - 4; + EncodeByteBlock(&finalBytes[0], encoded_string, iEncodedByte); + + // add '=' at the end + for (size_t i = 0; i < 4 * extraBytes / 3; i++) + encoded_string[encodedBytes - i - 1] = '='; + } + return encoded_string; +} + +} // !Util +} // !FBX +} // !Assimp + +#endif diff --git a/third_party/libassimp/code/FBXUtil.h b/third_party/libassimp/code/FBX/FBXUtil.h similarity index 75% rename from third_party/libassimp/code/FBXUtil.h rename to third_party/libassimp/code/FBX/FBXUtil.h index caea7f115c..b634418858 100644 --- a/third_party/libassimp/code/FBXUtil.h +++ b/third_party/libassimp/code/FBX/FBXUtil.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -48,6 +48,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "FBXCompileConfig.h" #include "FBXTokenizer.h" +#include namespace Assimp { namespace FBX { @@ -77,7 +78,7 @@ const char* TokenTypeString(TokenType t); * @param line Line index, 1-based * @param column Column index, 1-based * @return A string of the following format: {prefix} (offset 0x{offset}) {text}*/ -std::string AddOffset(const std::string& prefix, const std::string& text, unsigned int offset); +std::string AddOffset(const std::string& prefix, const std::string& text, size_t offset); /** Format log/error messages using a given line location in the source file. @@ -98,6 +99,37 @@ std::string AddLineAndColumn(const std::string& prefix, const std::string& text, * @return A string of the following format: {prefix} ({token-type}, line {line}, col {column}) {text}*/ std::string AddTokenText(const std::string& prefix, const std::string& text, const Token* tok); +/** Decode a single Base64-encoded character. +* +* @param ch Character to decode (from base64 to binary). +* @return decoded byte value*/ +uint8_t DecodeBase64(char ch); + +/** Compute decoded size of a Base64-encoded string +* +* @param in Characters to decode. +* @param inLength Number of characters to decode. +* @return size of the decoded data (number of bytes)*/ +size_t ComputeDecodedSizeBase64(const char* in, size_t inLength); + +/** Decode a Base64-encoded string +* +* @param in Characters to decode. +* @param inLength Number of characters to decode. +* @param out Pointer where we will store the decoded data. +* @param maxOutLength Size of output buffer. +* @return size of the decoded data (number of bytes)*/ +size_t DecodeBase64(const char* in, size_t inLength, uint8_t* out, size_t maxOutLength); + +char EncodeBase64(char byte); + +/** Encode bytes in base64-encoding +* +* @param data Binary data to encode. +* @param inLength Number of bytes to encode. +* @return base64-encoded string*/ +std::string EncodeBase64(const char* data, size_t length); + } } } diff --git a/third_party/libassimp/code/FBXConverter.cpp b/third_party/libassimp/code/FBXConverter.cpp deleted file mode 100644 index 0cbe04d8fe..0000000000 --- a/third_party/libassimp/code/FBXConverter.cpp +++ /dev/null @@ -1,3092 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2018, 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 FBXConverter.cpp - * @brief Implementation of the FBX DOM -> aiScene converter - */ - -#ifndef ASSIMP_BUILD_NO_FBX_IMPORTER - -#include "FBXConverter.h" -#include "FBXParser.h" -#include "FBXMeshGeometry.h" -#include "FBXDocument.h" -#include "FBXUtil.h" -#include "FBXProperties.h" -#include "FBXImporter.h" -#include - -#include - -#include -#include -#include -#include -#include -#include - -namespace Assimp { -namespace FBX { - -using namespace Util; - -#define MAGIC_NODE_TAG "_$AssimpFbx$" - -#define CONVERT_FBX_TIME(time) static_cast(time) / 46186158000L - -FBXConverter::FBXConverter( aiScene* out, const Document& doc ) -: defaultMaterialIndex() -, out( out ) -, doc( doc ) { - // animations need to be converted first since this will - // populate the node_anim_chain_bits map, which is needed - // to determine which nodes need to be generated. - ConvertAnimations(); - ConvertRootNode(); - - if ( doc.Settings().readAllMaterials ) { - // unfortunately this means we have to evaluate all objects - for( const ObjectMap::value_type& v : doc.Objects() ) { - - const Object* ob = v.second->Get(); - if ( !ob ) { - continue; - } - - const Material* mat = dynamic_cast( ob ); - if ( mat ) { - - if ( materials_converted.find( mat ) == materials_converted.end() ) { - ConvertMaterial( *mat, 0 ); - } - } - } - } - - ConvertGlobalSettings(); - TransferDataToScene(); - - // if we didn't read any meshes set the AI_SCENE_FLAGS_INCOMPLETE - // to make sure the scene passes assimp's validation. FBX files - // need not contain geometry (i.e. camera animations, raw armatures). - if ( out->mNumMeshes == 0 ) { - out->mFlags |= AI_SCENE_FLAGS_INCOMPLETE; - } -} - - -FBXConverter::~FBXConverter() { - std::for_each( meshes.begin(), meshes.end(), Util::delete_fun() ); - std::for_each( materials.begin(), materials.end(), Util::delete_fun() ); - std::for_each( animations.begin(), animations.end(), Util::delete_fun() ); - std::for_each( lights.begin(), lights.end(), Util::delete_fun() ); - std::for_each( cameras.begin(), cameras.end(), Util::delete_fun() ); - std::for_each( textures.begin(), textures.end(), Util::delete_fun() ); -} - -void FBXConverter::ConvertRootNode() { - out->mRootNode = new aiNode(); - out->mRootNode->mName.Set( "RootNode" ); - - // root has ID 0 - ConvertNodes( 0L, *out->mRootNode ); -} - -void FBXConverter::ConvertNodes( uint64_t id, aiNode& parent, const aiMatrix4x4& parent_transform ) { - const std::vector& conns = doc.GetConnectionsByDestinationSequenced( id, "Model" ); - - std::vector nodes; - nodes.reserve( conns.size() ); - - std::vector nodes_chain; - std::vector post_nodes_chain; - - try { - for( const Connection* con : conns ) { - - // ignore object-property links - if ( con->PropertyName().length() ) { - continue; - } - - const Object* const object = con->SourceObject(); - if ( nullptr == object ) { - FBXImporter::LogWarn( "failed to convert source object for Model link" ); - continue; - } - - const Model* const model = dynamic_cast( object ); - - if ( nullptr != model ) { - nodes_chain.clear(); - post_nodes_chain.clear(); - - aiMatrix4x4 new_abs_transform = parent_transform; - - // even though there is only a single input node, the design of - // assimp (or rather: the complicated transformation chain that - // is employed by fbx) means that we may need multiple aiNode's - // to represent a fbx node's transformation. - GenerateTransformationNodeChain( *model, nodes_chain, post_nodes_chain ); - - ai_assert( nodes_chain.size() ); - - std::string original_name = FixNodeName( model->Name() ); - - // check if any of the nodes in the chain has the name the fbx node - // is supposed to have. If there is none, add another node to - // preserve the name - people might have scripts etc. that rely - // on specific node names. - aiNode* name_carrier = NULL; - for( aiNode* prenode : nodes_chain ) { - if ( !strcmp( prenode->mName.C_Str(), original_name.c_str() ) ) { - name_carrier = prenode; - break; - } - } - - if ( !name_carrier ) { - std::string old_original_name = original_name; - GetUniqueName(old_original_name, original_name); - nodes_chain.push_back( new aiNode( original_name ) ); - } else { - original_name = nodes_chain.back()->mName.C_Str(); - } - - //setup metadata on newest node - SetupNodeMetadata( *model, *nodes_chain.back() ); - - // link all nodes in a row - aiNode* last_parent = &parent; - for( aiNode* prenode : nodes_chain ) { - ai_assert( prenode ); - - if ( last_parent != &parent ) { - last_parent->mNumChildren = 1; - last_parent->mChildren = new aiNode*[ 1 ]; - last_parent->mChildren[ 0 ] = prenode; - } - - prenode->mParent = last_parent; - last_parent = prenode; - - new_abs_transform *= prenode->mTransformation; - } - - // attach geometry - ConvertModel( *model, *nodes_chain.back(), new_abs_transform ); - - // check if there will be any child nodes - const std::vector& child_conns - = doc.GetConnectionsByDestinationSequenced( model->ID(), "Model" ); - - // if so, link the geometric transform inverse nodes - // before we attach any child nodes - if (child_conns.size()) { - for( aiNode* postnode : post_nodes_chain ) { - ai_assert( postnode ); - - if ( last_parent != &parent ) { - last_parent->mNumChildren = 1; - last_parent->mChildren = new aiNode*[ 1 ]; - last_parent->mChildren[ 0 ] = postnode; - } - - postnode->mParent = last_parent; - last_parent = postnode; - - new_abs_transform *= postnode->mTransformation; - } - } else { - // free the nodes we allocated as we don't need them - Util::delete_fun deleter; - std::for_each( - post_nodes_chain.begin(), - post_nodes_chain.end(), - deleter - ); - } - - // attach sub-nodes (if any) - ConvertNodes( model->ID(), *last_parent, new_abs_transform ); - - if ( doc.Settings().readLights ) { - ConvertLights( *model, original_name ); - } - - if ( doc.Settings().readCameras ) { - ConvertCameras( *model, original_name ); - } - - nodes.push_back( nodes_chain.front() ); - nodes_chain.clear(); - } - } - - if ( nodes.size() ) { - parent.mChildren = new aiNode*[ nodes.size() ](); - parent.mNumChildren = static_cast( nodes.size() ); - - std::swap_ranges( nodes.begin(), nodes.end(), parent.mChildren ); - } - } - catch ( std::exception& ) { - Util::delete_fun deleter; - std::for_each( nodes.begin(), nodes.end(), deleter ); - std::for_each( nodes_chain.begin(), nodes_chain.end(), deleter ); - std::for_each( post_nodes_chain.begin(), post_nodes_chain.end(), deleter ); - } -} - - -void FBXConverter::ConvertLights( const Model& model, const std::string &orig_name ) { - const std::vector& node_attrs = model.GetAttributes(); - for( const NodeAttribute* attr : node_attrs ) { - const Light* const light = dynamic_cast( attr ); - if ( light ) { - ConvertLight( *light, orig_name ); - } - } -} - -void FBXConverter::ConvertCameras( const Model& model, const std::string &orig_name ) { - const std::vector& node_attrs = model.GetAttributes(); - for( const NodeAttribute* attr : node_attrs ) { - const Camera* const cam = dynamic_cast( attr ); - if ( cam ) { - ConvertCamera( *cam, orig_name ); - } - } -} - -void FBXConverter::ConvertLight( const Light& light, const std::string &orig_name ) { - lights.push_back( new aiLight() ); - aiLight* const out_light = lights.back(); - - out_light->mName.Set( orig_name ); - - const float intensity = light.Intensity() / 100.0f; - const aiVector3D& col = light.Color(); - - out_light->mColorDiffuse = aiColor3D( col.x, col.y, col.z ); - out_light->mColorDiffuse.r *= intensity; - out_light->mColorDiffuse.g *= intensity; - out_light->mColorDiffuse.b *= intensity; - - out_light->mColorSpecular = out_light->mColorDiffuse; - - //lights are defined along negative y direction - out_light->mPosition = aiVector3D(0.0f); - out_light->mDirection = aiVector3D(0.0f, -1.0f, 0.0f); - out_light->mUp = aiVector3D(0.0f, 0.0f, -1.0f); - - switch ( light.LightType() ) - { - case Light::Type_Point: - out_light->mType = aiLightSource_POINT; - break; - - case Light::Type_Directional: - out_light->mType = aiLightSource_DIRECTIONAL; - break; - - case Light::Type_Spot: - out_light->mType = aiLightSource_SPOT; - out_light->mAngleOuterCone = AI_DEG_TO_RAD( light.OuterAngle() ); - out_light->mAngleInnerCone = AI_DEG_TO_RAD( light.InnerAngle() ); - break; - - case Light::Type_Area: - FBXImporter::LogWarn( "cannot represent area light, set to UNDEFINED" ); - out_light->mType = aiLightSource_UNDEFINED; - break; - - case Light::Type_Volume: - FBXImporter::LogWarn( "cannot represent volume light, set to UNDEFINED" ); - out_light->mType = aiLightSource_UNDEFINED; - break; - default: - ai_assert( false ); - } - - float decay = light.DecayStart(); - switch ( light.DecayType() ) - { - case Light::Decay_None: - out_light->mAttenuationConstant = decay; - out_light->mAttenuationLinear = 0.0f; - out_light->mAttenuationQuadratic = 0.0f; - break; - case Light::Decay_Linear: - out_light->mAttenuationConstant = 0.0f; - out_light->mAttenuationLinear = 2.0f / decay; - out_light->mAttenuationQuadratic = 0.0f; - break; - case Light::Decay_Quadratic: - out_light->mAttenuationConstant = 0.0f; - out_light->mAttenuationLinear = 0.0f; - out_light->mAttenuationQuadratic = 2.0f / (decay * decay); - break; - case Light::Decay_Cubic: - FBXImporter::LogWarn( "cannot represent cubic attenuation, set to Quadratic" ); - out_light->mAttenuationQuadratic = 1.0f; - break; - default: - ai_assert( false ); - } -} - -void FBXConverter::ConvertCamera( const Camera& cam, const std::string &orig_name ) -{ - cameras.push_back( new aiCamera() ); - aiCamera* const out_camera = cameras.back(); - - out_camera->mName.Set( orig_name ); - - out_camera->mAspect = cam.AspectWidth() / cam.AspectHeight(); - - //cameras are defined along positive x direction - out_camera->mPosition = cam.Position(); - out_camera->mLookAt = ( cam.InterestPosition() - out_camera->mPosition ).Normalize(); - out_camera->mUp = cam.UpVector(); - - out_camera->mHorizontalFOV = AI_DEG_TO_RAD( cam.FieldOfView() ); - out_camera->mClipPlaneNear = cam.NearPlane(); - out_camera->mClipPlaneFar = cam.FarPlane(); -} - -void FBXConverter::GetUniqueName( const std::string &name, std::string &uniqueName ) -{ - int i = 0; - uniqueName = name; - while (mNodeNames.find(uniqueName) != mNodeNames.end()) - { - ++i; - std::stringstream ext; - ext << name << std::setfill('0') << std::setw(3) << i; - uniqueName = ext.str(); - } - mNodeNames.insert(uniqueName); -} - - -const char* FBXConverter::NameTransformationComp( TransformationComp comp ) { - switch ( comp ) { - case TransformationComp_Translation: - return "Translation"; - case TransformationComp_RotationOffset: - return "RotationOffset"; - case TransformationComp_RotationPivot: - return "RotationPivot"; - case TransformationComp_PreRotation: - return "PreRotation"; - case TransformationComp_Rotation: - return "Rotation"; - case TransformationComp_PostRotation: - return "PostRotation"; - case TransformationComp_RotationPivotInverse: - return "RotationPivotInverse"; - case TransformationComp_ScalingOffset: - return "ScalingOffset"; - case TransformationComp_ScalingPivot: - return "ScalingPivot"; - case TransformationComp_Scaling: - return "Scaling"; - case TransformationComp_ScalingPivotInverse: - return "ScalingPivotInverse"; - case TransformationComp_GeometricScaling: - return "GeometricScaling"; - case TransformationComp_GeometricRotation: - return "GeometricRotation"; - case TransformationComp_GeometricTranslation: - return "GeometricTranslation"; - case TransformationComp_GeometricScalingInverse: - return "GeometricScalingInverse"; - case TransformationComp_GeometricRotationInverse: - return "GeometricRotationInverse"; - case TransformationComp_GeometricTranslationInverse: - return "GeometricTranslationInverse"; - case TransformationComp_MAXIMUM: // this is to silence compiler warnings - default: - break; - } - - ai_assert( false ); - - return nullptr; -} - -const char* FBXConverter::NameTransformationCompProperty( TransformationComp comp ) { - switch ( comp ) { - case TransformationComp_Translation: - return "Lcl Translation"; - case TransformationComp_RotationOffset: - return "RotationOffset"; - case TransformationComp_RotationPivot: - return "RotationPivot"; - case TransformationComp_PreRotation: - return "PreRotation"; - case TransformationComp_Rotation: - return "Lcl Rotation"; - case TransformationComp_PostRotation: - return "PostRotation"; - case TransformationComp_RotationPivotInverse: - return "RotationPivotInverse"; - case TransformationComp_ScalingOffset: - return "ScalingOffset"; - case TransformationComp_ScalingPivot: - return "ScalingPivot"; - case TransformationComp_Scaling: - return "Lcl Scaling"; - case TransformationComp_ScalingPivotInverse: - return "ScalingPivotInverse"; - case TransformationComp_GeometricScaling: - return "GeometricScaling"; - case TransformationComp_GeometricRotation: - return "GeometricRotation"; - case TransformationComp_GeometricTranslation: - return "GeometricTranslation"; - case TransformationComp_GeometricScalingInverse: - return "GeometricScalingInverse"; - case TransformationComp_GeometricRotationInverse: - return "GeometricRotationInverse"; - case TransformationComp_GeometricTranslationInverse: - return "GeometricTranslationInverse"; - case TransformationComp_MAXIMUM: // this is to silence compiler warnings - break; - } - - ai_assert( false ); - - return nullptr; -} - -aiVector3D FBXConverter::TransformationCompDefaultValue( TransformationComp comp ) -{ - // XXX a neat way to solve the never-ending special cases for scaling - // would be to do everything in log space! - return comp == TransformationComp_Scaling ? aiVector3D( 1.f, 1.f, 1.f ) : aiVector3D(); -} - -void FBXConverter::GetRotationMatrix( Model::RotOrder mode, const aiVector3D& rotation, aiMatrix4x4& out ) -{ - if ( mode == Model::RotOrder_SphericXYZ ) { - FBXImporter::LogError( "Unsupported RotationMode: SphericXYZ" ); - out = aiMatrix4x4(); - return; - } - - const float angle_epsilon = 1e-6f; - - out = aiMatrix4x4(); - - bool is_id[ 3 ] = { true, true, true }; - - aiMatrix4x4 temp[ 3 ]; - if ( std::fabs( rotation.z ) > angle_epsilon ) { - aiMatrix4x4::RotationZ( AI_DEG_TO_RAD( rotation.z ), temp[ 2 ] ); - is_id[ 2 ] = false; - } - if ( std::fabs( rotation.y ) > angle_epsilon ) { - aiMatrix4x4::RotationY( AI_DEG_TO_RAD( rotation.y ), temp[ 1 ] ); - is_id[ 1 ] = false; - } - if ( std::fabs( rotation.x ) > angle_epsilon ) { - aiMatrix4x4::RotationX( AI_DEG_TO_RAD( rotation.x ), temp[ 0 ] ); - is_id[ 0 ] = false; - } - - int order[ 3 ] = { -1, -1, -1 }; - - // note: rotation order is inverted since we're left multiplying as is usual in assimp - switch ( mode ) - { - case Model::RotOrder_EulerXYZ: - order[ 0 ] = 2; - order[ 1 ] = 1; - order[ 2 ] = 0; - break; - - case Model::RotOrder_EulerXZY: - order[ 0 ] = 1; - order[ 1 ] = 2; - order[ 2 ] = 0; - break; - - case Model::RotOrder_EulerYZX: - order[ 0 ] = 0; - order[ 1 ] = 2; - order[ 2 ] = 1; - break; - - case Model::RotOrder_EulerYXZ: - order[ 0 ] = 2; - order[ 1 ] = 0; - order[ 2 ] = 1; - break; - - case Model::RotOrder_EulerZXY: - order[ 0 ] = 1; - order[ 1 ] = 0; - order[ 2 ] = 2; - break; - - case Model::RotOrder_EulerZYX: - order[ 0 ] = 0; - order[ 1 ] = 1; - order[ 2 ] = 2; - break; - - default: - ai_assert( false ); - break; - } - - ai_assert( order[ 0 ] >= 0 ); - ai_assert( order[ 0 ] <= 2 ); - ai_assert( order[ 1 ] >= 0 ); - ai_assert( order[ 1 ] <= 2 ); - ai_assert( order[ 2 ] >= 0 ); - ai_assert( order[ 2 ] <= 2 ); - - if ( !is_id[ order[ 0 ] ] ) { - out = temp[ order[ 0 ] ]; - } - - if ( !is_id[ order[ 1 ] ] ) { - out = out * temp[ order[ 1 ] ]; - } - - if ( !is_id[ order[ 2 ] ] ) { - out = out * temp[ order[ 2 ] ]; - } -} - -bool FBXConverter::NeedsComplexTransformationChain( const Model& model ) -{ - const PropertyTable& props = model.Props(); - bool ok; - - const float zero_epsilon = 1e-6f; - const aiVector3D all_ones(1.0f, 1.0f, 1.0f); - for ( size_t i = 0; i < TransformationComp_MAXIMUM; ++i ) { - const TransformationComp comp = static_cast< TransformationComp >( i ); - - if ( comp == TransformationComp_Rotation || comp == TransformationComp_Scaling || comp == TransformationComp_Translation ) { - continue; - } - - bool scale_compare = ( comp == TransformationComp_GeometricScaling || comp == TransformationComp_Scaling ); - - const aiVector3D& v = PropertyGet( props, NameTransformationCompProperty( comp ), ok ); - if ( ok && scale_compare ) { - if ( (v - all_ones).SquareLength() > zero_epsilon ) { - return true; - } - } else if ( ok ) { - if ( v.SquareLength() > zero_epsilon ) { - return true; - } - } - } - - return false; -} - -std::string FBXConverter::NameTransformationChainNode( const std::string& name, TransformationComp comp ) -{ - return name + std::string( MAGIC_NODE_TAG ) + "_" + NameTransformationComp( comp ); -} - -void FBXConverter::GenerateTransformationNodeChain( const Model& model, std::vector& output_nodes, - std::vector& post_output_nodes ) { - const PropertyTable& props = model.Props(); - const Model::RotOrder rot = model.RotationOrder(); - - bool ok; - - aiMatrix4x4 chain[ TransformationComp_MAXIMUM ]; - std::fill_n( chain, static_cast( TransformationComp_MAXIMUM ), aiMatrix4x4() ); - - // generate transformation matrices for all the different transformation components - const float zero_epsilon = 1e-6f; - const aiVector3D all_ones(1.0f, 1.0f, 1.0f); - bool is_complex = false; - - const aiVector3D& PreRotation = PropertyGet( props, "PreRotation", ok ); - if ( ok && PreRotation.SquareLength() > zero_epsilon ) { - is_complex = true; - - GetRotationMatrix( Model::RotOrder::RotOrder_EulerXYZ, PreRotation, chain[ TransformationComp_PreRotation ] ); - } - - const aiVector3D& PostRotation = PropertyGet( props, "PostRotation", ok ); - if ( ok && PostRotation.SquareLength() > zero_epsilon ) { - is_complex = true; - - GetRotationMatrix( Model::RotOrder::RotOrder_EulerXYZ, PostRotation, chain[ TransformationComp_PostRotation ] ); - } - - const aiVector3D& RotationPivot = PropertyGet( props, "RotationPivot", ok ); - if ( ok && RotationPivot.SquareLength() > zero_epsilon ) { - is_complex = true; - - aiMatrix4x4::Translation( RotationPivot, chain[ TransformationComp_RotationPivot ] ); - aiMatrix4x4::Translation( -RotationPivot, chain[ TransformationComp_RotationPivotInverse ] ); - } - - const aiVector3D& RotationOffset = PropertyGet( props, "RotationOffset", ok ); - if ( ok && RotationOffset.SquareLength() > zero_epsilon ) { - is_complex = true; - - aiMatrix4x4::Translation( RotationOffset, chain[ TransformationComp_RotationOffset ] ); - } - - const aiVector3D& ScalingOffset = PropertyGet( props, "ScalingOffset", ok ); - if ( ok && ScalingOffset.SquareLength() > zero_epsilon ) { - is_complex = true; - - aiMatrix4x4::Translation( ScalingOffset, chain[ TransformationComp_ScalingOffset ] ); - } - - const aiVector3D& ScalingPivot = PropertyGet( props, "ScalingPivot", ok ); - if ( ok && ScalingPivot.SquareLength() > zero_epsilon ) { - is_complex = true; - - aiMatrix4x4::Translation( ScalingPivot, chain[ TransformationComp_ScalingPivot ] ); - aiMatrix4x4::Translation( -ScalingPivot, chain[ TransformationComp_ScalingPivotInverse ] ); - } - - const aiVector3D& Translation = PropertyGet( props, "Lcl Translation", ok ); - if ( ok && Translation.SquareLength() > zero_epsilon ) { - aiMatrix4x4::Translation( Translation, chain[ TransformationComp_Translation ] ); - } - - const aiVector3D& Scaling = PropertyGet( props, "Lcl Scaling", ok ); - if ( ok && (Scaling - all_ones).SquareLength() > zero_epsilon ) { - aiMatrix4x4::Scaling( Scaling, chain[ TransformationComp_Scaling ] ); - } - - const aiVector3D& Rotation = PropertyGet( props, "Lcl Rotation", ok ); - if ( ok && Rotation.SquareLength() > zero_epsilon ) { - GetRotationMatrix( rot, Rotation, chain[ TransformationComp_Rotation ] ); - } - - const aiVector3D& GeometricScaling = PropertyGet( props, "GeometricScaling", ok ); - if ( ok && (GeometricScaling - all_ones).SquareLength() > zero_epsilon ) { - is_complex = true; - aiMatrix4x4::Scaling( GeometricScaling, chain[ TransformationComp_GeometricScaling ] ); - aiVector3D GeometricScalingInverse = GeometricScaling; - bool canscale = true; - for (unsigned int i = 0; i < 3; ++i) { - if ( std::fabs( GeometricScalingInverse[i] ) > zero_epsilon ) { - GeometricScalingInverse[i] = 1.0f / GeometricScaling[i]; - } else { - FBXImporter::LogError( "cannot invert geometric scaling matrix with a 0.0 scale component" ); - canscale = false; - break; - } - } - if (canscale) { - aiMatrix4x4::Scaling( GeometricScalingInverse, chain[ TransformationComp_GeometricScalingInverse ] ); - } - } - - const aiVector3D& GeometricRotation = PropertyGet( props, "GeometricRotation", ok ); - if ( ok && GeometricRotation.SquareLength() > zero_epsilon ) { - is_complex = true; - GetRotationMatrix( rot, GeometricRotation, chain[ TransformationComp_GeometricRotation ] ); - GetRotationMatrix( rot, GeometricRotation, chain[ TransformationComp_GeometricRotationInverse ] ); - chain[ TransformationComp_GeometricRotationInverse ].Inverse(); - } - - const aiVector3D& GeometricTranslation = PropertyGet( props, "GeometricTranslation", ok ); - if ( ok && GeometricTranslation.SquareLength() > zero_epsilon ) { - is_complex = true; - aiMatrix4x4::Translation( GeometricTranslation, chain[ TransformationComp_GeometricTranslation ] ); - aiMatrix4x4::Translation( -GeometricTranslation, chain[ TransformationComp_GeometricTranslationInverse ] ); - } - - // is_complex needs to be consistent with NeedsComplexTransformationChain() - // or the interplay between this code and the animation converter would - // not be guaranteed. - ai_assert( NeedsComplexTransformationChain( model ) == is_complex ); - - std::string name = FixNodeName( model.Name() ); - - // now, if we have more than just Translation, Scaling and Rotation, - // we need to generate a full node chain to accommodate for assimp's - // lack to express pivots and offsets. - if ( is_complex && doc.Settings().preservePivots ) { - FBXImporter::LogInfo( "generating full transformation chain for node: " + name ); - - // query the anim_chain_bits dictionary to find out which chain elements - // have associated node animation channels. These can not be dropped - // even if they have identity transform in bind pose. - NodeAnimBitMap::const_iterator it = node_anim_chain_bits.find( name ); - const unsigned int anim_chain_bitmask = ( it == node_anim_chain_bits.end() ? 0 : ( *it ).second ); - - unsigned int bit = 0x1; - for ( size_t i = 0; i < TransformationComp_MAXIMUM; ++i, bit <<= 1 ) { - const TransformationComp comp = static_cast( i ); - - if ( chain[ i ].IsIdentity() && ( anim_chain_bitmask & bit ) == 0 ) { - continue; - } - - if ( comp == TransformationComp_PostRotation ) { - chain[ i ] = chain[ i ].Inverse(); - } - - aiNode* nd = new aiNode(); - nd->mName.Set( NameTransformationChainNode( name, comp ) ); - nd->mTransformation = chain[ i ]; - - // geometric inverses go in a post-node chain - if ( comp == TransformationComp_GeometricScalingInverse || - comp == TransformationComp_GeometricRotationInverse || - comp == TransformationComp_GeometricTranslationInverse - ) { - post_output_nodes.push_back( nd ); - } else { - output_nodes.push_back( nd ); - } - } - - ai_assert( output_nodes.size() ); - return; - } - - // else, we can just multiply the matrices together - aiNode* nd = new aiNode(); - output_nodes.push_back( nd ); - std::string uniqueName; - GetUniqueName( name, uniqueName ); - - nd->mName.Set( uniqueName ); - - for (const auto &transform : chain) { - nd->mTransformation = nd->mTransformation * transform; - } -} - -void FBXConverter::SetupNodeMetadata( const Model& model, aiNode& nd ) -{ - const PropertyTable& props = model.Props(); - DirectPropertyMap unparsedProperties = props.GetUnparsedProperties(); - - // create metadata on node - const std::size_t numStaticMetaData = 2; - aiMetadata* data = aiMetadata::Alloc( static_cast(unparsedProperties.size() + numStaticMetaData) ); - nd.mMetaData = data; - int index = 0; - - // find user defined properties (3ds Max) - data->Set( index++, "UserProperties", aiString( PropertyGet( props, "UDP3DSMAX", "" ) ) ); - // preserve the info that a node was marked as Null node in the original file. - data->Set( index++, "IsNull", model.IsNull() ? true : false ); - - // add unparsed properties to the node's metadata - for( const DirectPropertyMap::value_type& prop : unparsedProperties ) { - // Interpret the property as a concrete type - if ( const TypedProperty* interpreted = prop.second->As >() ) { - data->Set( index++, prop.first, interpreted->Value() ); - } else if ( const TypedProperty* interpreted = prop.second->As >() ) { - data->Set( index++, prop.first, interpreted->Value() ); - } else if ( const TypedProperty* interpreted = prop.second->As >() ) { - data->Set( index++, prop.first, interpreted->Value() ); - } else if ( const TypedProperty* interpreted = prop.second->As >() ) { - data->Set( index++, prop.first, interpreted->Value() ); - } else if ( const TypedProperty* interpreted = prop.second->As >() ) { - data->Set( index++, prop.first, aiString( interpreted->Value() ) ); - } else if ( const TypedProperty* interpreted = prop.second->As >() ) { - data->Set( index++, prop.first, interpreted->Value() ); - } else { - ai_assert( false ); - } - } -} - -void FBXConverter::ConvertModel( const Model& model, aiNode& nd, const aiMatrix4x4& node_global_transform ) -{ - const std::vector& geos = model.GetGeometry(); - - std::vector meshes; - meshes.reserve( geos.size() ); - - for( const Geometry* geo : geos ) { - - const MeshGeometry* const mesh = dynamic_cast< const MeshGeometry* >( geo ); - if ( mesh ) { - const std::vector& indices = ConvertMesh( *mesh, model, node_global_transform, nd); - std::copy( indices.begin(), indices.end(), std::back_inserter( meshes ) ); - } - else { - FBXImporter::LogWarn( "ignoring unrecognized geometry: " + geo->Name() ); - } - } - - if ( meshes.size() ) { - nd.mMeshes = new unsigned int[ meshes.size() ](); - nd.mNumMeshes = static_cast< unsigned int >( meshes.size() ); - - std::swap_ranges( meshes.begin(), meshes.end(), nd.mMeshes ); - } -} - -std::vector FBXConverter::ConvertMesh( const MeshGeometry& mesh, const Model& model, - const aiMatrix4x4& node_global_transform, aiNode& nd) -{ - std::vector temp; - - MeshMap::const_iterator it = meshes_converted.find( &mesh ); - if ( it != meshes_converted.end() ) { - std::copy( ( *it ).second.begin(), ( *it ).second.end(), std::back_inserter( temp ) ); - return temp; - } - - const std::vector& vertices = mesh.GetVertices(); - const std::vector& faces = mesh.GetFaceIndexCounts(); - if ( vertices.empty() || faces.empty() ) { - FBXImporter::LogWarn( "ignoring empty geometry: " + mesh.Name() ); - return temp; - } - - // one material per mesh maps easily to aiMesh. Multiple material - // meshes need to be split. - const MatIndexArray& mindices = mesh.GetMaterialIndices(); - if ( doc.Settings().readMaterials && !mindices.empty() ) { - const MatIndexArray::value_type base = mindices[ 0 ]; - for( MatIndexArray::value_type index : mindices ) { - if ( index != base ) { - return ConvertMeshMultiMaterial( mesh, model, node_global_transform, nd); - } - } - } - - // faster code-path, just copy the data - temp.push_back( ConvertMeshSingleMaterial( mesh, model, node_global_transform, nd) ); - return temp; -} - -aiMesh* FBXConverter::SetupEmptyMesh( const MeshGeometry& mesh, aiNode& nd) -{ - aiMesh* const out_mesh = new aiMesh(); - meshes.push_back( out_mesh ); - meshes_converted[ &mesh ].push_back( static_cast( meshes.size() - 1 ) ); - - // set name - std::string name = mesh.Name(); - if ( name.substr( 0, 10 ) == "Geometry::" ) { - name = name.substr( 10 ); - } - - if ( name.length() ) { - out_mesh->mName.Set( name ); - } - else - { - out_mesh->mName = nd.mName; - } - - return out_mesh; -} - -unsigned int FBXConverter::ConvertMeshSingleMaterial( const MeshGeometry& mesh, const Model& model, - const aiMatrix4x4& node_global_transform, aiNode& nd) -{ - const MatIndexArray& mindices = mesh.GetMaterialIndices(); - aiMesh* const out_mesh = SetupEmptyMesh(mesh, nd); - - const std::vector& vertices = mesh.GetVertices(); - const std::vector& faces = mesh.GetFaceIndexCounts(); - - // copy vertices - out_mesh->mNumVertices = static_cast( vertices.size() ); - out_mesh->mVertices = new aiVector3D[ vertices.size() ]; - std::copy( vertices.begin(), vertices.end(), out_mesh->mVertices ); - - // generate dummy faces - out_mesh->mNumFaces = static_cast( faces.size() ); - aiFace* fac = out_mesh->mFaces = new aiFace[ faces.size() ](); - - unsigned int cursor = 0; - for( unsigned int pcount : faces ) { - aiFace& f = *fac++; - f.mNumIndices = pcount; - f.mIndices = new unsigned int[ pcount ]; - switch ( pcount ) - { - case 1: - out_mesh->mPrimitiveTypes |= aiPrimitiveType_POINT; - break; - case 2: - out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE; - break; - case 3: - out_mesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE; - break; - default: - out_mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON; - break; - } - for ( unsigned int i = 0; i < pcount; ++i ) { - f.mIndices[ i ] = cursor++; - } - } - - // copy normals - const std::vector& normals = mesh.GetNormals(); - if ( normals.size() ) { - ai_assert( normals.size() == vertices.size() ); - - out_mesh->mNormals = new aiVector3D[ vertices.size() ]; - std::copy( normals.begin(), normals.end(), out_mesh->mNormals ); - } - - // copy tangents - assimp requires both tangents and bitangents (binormals) - // to be present, or neither of them. Compute binormals from normals - // and tangents if needed. - const std::vector& tangents = mesh.GetTangents(); - const std::vector* binormals = &mesh.GetBinormals(); - - if ( tangents.size() ) { - std::vector tempBinormals; - if ( !binormals->size() ) { - if ( normals.size() ) { - tempBinormals.resize( normals.size() ); - for ( unsigned int i = 0; i < tangents.size(); ++i ) { - tempBinormals[ i ] = normals[ i ] ^ tangents[ i ]; - } - - binormals = &tempBinormals; - } - else { - binormals = NULL; - } - } - - if ( binormals ) { - ai_assert( tangents.size() == vertices.size() ); - ai_assert( binormals->size() == vertices.size() ); - - out_mesh->mTangents = new aiVector3D[ vertices.size() ]; - std::copy( tangents.begin(), tangents.end(), out_mesh->mTangents ); - - out_mesh->mBitangents = new aiVector3D[ vertices.size() ]; - std::copy( binormals->begin(), binormals->end(), out_mesh->mBitangents ); - } - } - - // copy texture coords - for ( unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i ) { - const std::vector& uvs = mesh.GetTextureCoords( i ); - if ( uvs.empty() ) { - break; - } - - aiVector3D* out_uv = out_mesh->mTextureCoords[ i ] = new aiVector3D[ vertices.size() ]; - for( const aiVector2D& v : uvs ) { - *out_uv++ = aiVector3D( v.x, v.y, 0.0f ); - } - - out_mesh->mNumUVComponents[ i ] = 2; - } - - // copy vertex colors - for ( unsigned int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i ) { - const std::vector& colors = mesh.GetVertexColors( i ); - if ( colors.empty() ) { - break; - } - - out_mesh->mColors[ i ] = new aiColor4D[ vertices.size() ]; - std::copy( colors.begin(), colors.end(), out_mesh->mColors[ i ] ); - } - - if ( !doc.Settings().readMaterials || mindices.empty() ) { - FBXImporter::LogError( "no material assigned to mesh, setting default material" ); - out_mesh->mMaterialIndex = GetDefaultMaterial(); - } - else { - ConvertMaterialForMesh( out_mesh, model, mesh, mindices[ 0 ] ); - } - - if ( doc.Settings().readWeights && mesh.DeformerSkin() != NULL ) { - ConvertWeights( out_mesh, model, mesh, node_global_transform, NO_MATERIAL_SEPARATION ); - } - - return static_cast( meshes.size() - 1 ); -} - -std::vector FBXConverter::ConvertMeshMultiMaterial( const MeshGeometry& mesh, const Model& model, - const aiMatrix4x4& node_global_transform, aiNode& nd) -{ - const MatIndexArray& mindices = mesh.GetMaterialIndices(); - ai_assert( mindices.size() ); - - std::set had; - std::vector indices; - - for( MatIndexArray::value_type index : mindices ) { - if ( had.find( index ) == had.end() ) { - - indices.push_back( ConvertMeshMultiMaterial( mesh, model, index, node_global_transform, nd) ); - had.insert( index ); - } - } - - return indices; -} - -unsigned int FBXConverter::ConvertMeshMultiMaterial( const MeshGeometry& mesh, const Model& model, - MatIndexArray::value_type index, - const aiMatrix4x4& node_global_transform, - aiNode& nd) -{ - aiMesh* const out_mesh = SetupEmptyMesh(mesh, nd); - - const MatIndexArray& mindices = mesh.GetMaterialIndices(); - const std::vector& vertices = mesh.GetVertices(); - const std::vector& faces = mesh.GetFaceIndexCounts(); - - const bool process_weights = doc.Settings().readWeights && mesh.DeformerSkin() != NULL; - - unsigned int count_faces = 0; - unsigned int count_vertices = 0; - - // count faces - std::vector::const_iterator itf = faces.begin(); - for ( MatIndexArray::const_iterator it = mindices.begin(), - end = mindices.end(); it != end; ++it, ++itf ) - { - if ( ( *it ) != index ) { - continue; - } - ++count_faces; - count_vertices += *itf; - } - - ai_assert( count_faces ); - ai_assert( count_vertices ); - - // mapping from output indices to DOM indexing, needed to resolve weights - std::vector reverseMapping; - - if ( process_weights ) { - reverseMapping.resize( count_vertices ); - } - - // allocate output data arrays, but don't fill them yet - out_mesh->mNumVertices = count_vertices; - out_mesh->mVertices = new aiVector3D[ count_vertices ]; - - out_mesh->mNumFaces = count_faces; - aiFace* fac = out_mesh->mFaces = new aiFace[ count_faces ](); - - - // allocate normals - const std::vector& normals = mesh.GetNormals(); - if ( normals.size() ) { - ai_assert( normals.size() == vertices.size() ); - out_mesh->mNormals = new aiVector3D[ vertices.size() ]; - } - - // allocate tangents, binormals. - const std::vector& tangents = mesh.GetTangents(); - const std::vector* binormals = &mesh.GetBinormals(); - std::vector tempBinormals; - - if ( tangents.size() ) { - if ( !binormals->size() ) { - if ( normals.size() ) { - // XXX this computes the binormals for the entire mesh, not only - // the part for which we need them. - tempBinormals.resize( normals.size() ); - for ( unsigned int i = 0; i < tangents.size(); ++i ) { - tempBinormals[ i ] = normals[ i ] ^ tangents[ i ]; - } - - binormals = &tempBinormals; - } - else { - binormals = NULL; - } - } - - if ( binormals ) { - ai_assert( tangents.size() == vertices.size() && binormals->size() == vertices.size() ); - - out_mesh->mTangents = new aiVector3D[ vertices.size() ]; - out_mesh->mBitangents = new aiVector3D[ vertices.size() ]; - } - } - - // allocate texture coords - unsigned int num_uvs = 0; - for ( unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i, ++num_uvs ) { - const std::vector& uvs = mesh.GetTextureCoords( i ); - if ( uvs.empty() ) { - break; - } - - out_mesh->mTextureCoords[ i ] = new aiVector3D[ vertices.size() ]; - out_mesh->mNumUVComponents[ i ] = 2; - } - - // allocate vertex colors - unsigned int num_vcs = 0; - for ( unsigned int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i, ++num_vcs ) { - const std::vector& colors = mesh.GetVertexColors( i ); - if ( colors.empty() ) { - break; - } - - out_mesh->mColors[ i ] = new aiColor4D[ vertices.size() ]; - } - - unsigned int cursor = 0, in_cursor = 0; - - itf = faces.begin(); - for ( MatIndexArray::const_iterator it = mindices.begin(), - end = mindices.end(); it != end; ++it, ++itf ) - { - const unsigned int pcount = *itf; - if ( ( *it ) != index ) { - in_cursor += pcount; - continue; - } - - aiFace& f = *fac++; - - f.mNumIndices = pcount; - f.mIndices = new unsigned int[ pcount ]; - switch ( pcount ) - { - case 1: - out_mesh->mPrimitiveTypes |= aiPrimitiveType_POINT; - break; - case 2: - out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE; - break; - case 3: - out_mesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE; - break; - default: - out_mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON; - break; - } - for ( unsigned int i = 0; i < pcount; ++i, ++cursor, ++in_cursor ) { - f.mIndices[ i ] = cursor; - - if ( reverseMapping.size() ) { - reverseMapping[ cursor ] = in_cursor; - } - - out_mesh->mVertices[ cursor ] = vertices[ in_cursor ]; - - if ( out_mesh->mNormals ) { - out_mesh->mNormals[ cursor ] = normals[ in_cursor ]; - } - - if ( out_mesh->mTangents ) { - out_mesh->mTangents[ cursor ] = tangents[ in_cursor ]; - out_mesh->mBitangents[ cursor ] = ( *binormals )[ in_cursor ]; - } - - for ( unsigned int j = 0; j < num_uvs; ++j ) { - const std::vector& uvs = mesh.GetTextureCoords( j ); - out_mesh->mTextureCoords[ j ][ cursor ] = aiVector3D( uvs[ in_cursor ].x, uvs[ in_cursor ].y, 0.0f ); - } - - for ( unsigned int j = 0; j < num_vcs; ++j ) { - const std::vector& cols = mesh.GetVertexColors( j ); - out_mesh->mColors[ j ][ cursor ] = cols[ in_cursor ]; - } - } - } - - ConvertMaterialForMesh( out_mesh, model, mesh, index ); - - if ( process_weights ) { - ConvertWeights( out_mesh, model, mesh, node_global_transform, index, &reverseMapping ); - } - - return static_cast( meshes.size() - 1 ); -} - -void FBXConverter::ConvertWeights( aiMesh* out, const Model& model, const MeshGeometry& geo, - const aiMatrix4x4& node_global_transform , - unsigned int materialIndex, - std::vector* outputVertStartIndices ) -{ - ai_assert( geo.DeformerSkin() ); - - std::vector out_indices; - std::vector index_out_indices; - std::vector count_out_indices; - - const Skin& sk = *geo.DeformerSkin(); - - std::vector bones; - bones.reserve( sk.Clusters().size() ); - - const bool no_mat_check = materialIndex == NO_MATERIAL_SEPARATION; - ai_assert( no_mat_check || outputVertStartIndices ); - - try { - - for( const Cluster* cluster : sk.Clusters() ) { - ai_assert( cluster ); - - const WeightIndexArray& indices = cluster->GetIndices(); - - if ( indices.empty() ) { - continue; - } - - const MatIndexArray& mats = geo.GetMaterialIndices(); - - bool ok = false; - - const size_t no_index_sentinel = std::numeric_limits::max(); - - count_out_indices.clear(); - index_out_indices.clear(); - out_indices.clear(); - - // now check if *any* of these weights is contained in the output mesh, - // taking notes so we don't need to do it twice. - for( WeightIndexArray::value_type index : indices ) { - - unsigned int count = 0; - const unsigned int* const out_idx = geo.ToOutputVertexIndex( index, count ); - // ToOutputVertexIndex only returns NULL if index is out of bounds - // which should never happen - ai_assert( out_idx != NULL ); - - index_out_indices.push_back( no_index_sentinel ); - count_out_indices.push_back( 0 ); - - for ( unsigned int i = 0; i < count; ++i ) { - if ( no_mat_check || static_cast( mats[ geo.FaceForVertexIndex( out_idx[ i ] ) ] ) == materialIndex ) { - - if ( index_out_indices.back() == no_index_sentinel ) { - index_out_indices.back() = out_indices.size(); - - } - - if ( no_mat_check ) { - out_indices.push_back( out_idx[ i ] ); - } - else { - // this extra lookup is in O(logn), so the entire algorithm becomes O(nlogn) - const std::vector::iterator it = std::lower_bound( - outputVertStartIndices->begin(), - outputVertStartIndices->end(), - out_idx[ i ] - ); - - out_indices.push_back( std::distance( outputVertStartIndices->begin(), it ) ); - } - - ++count_out_indices.back(); - ok = true; - } - } - } - - // if we found at least one, generate the output bones - // XXX this could be heavily simplified by collecting the bone - // data in a single step. - if ( ok ) { - ConvertCluster( bones, model, *cluster, out_indices, index_out_indices, - count_out_indices, node_global_transform ); - } - } - } - catch ( std::exception& ) { - std::for_each( bones.begin(), bones.end(), Util::delete_fun() ); - throw; - } - - if ( bones.empty() ) { - return; - } - - out->mBones = new aiBone*[ bones.size() ](); - out->mNumBones = static_cast( bones.size() ); - - std::swap_ranges( bones.begin(), bones.end(), out->mBones ); -} - -void FBXConverter::ConvertCluster( std::vector& bones, const Model& /*model*/, const Cluster& cl, - std::vector& out_indices, - std::vector& index_out_indices, - std::vector& count_out_indices, - const aiMatrix4x4& node_global_transform ) -{ - - aiBone* const bone = new aiBone(); - bones.push_back( bone ); - - bone->mName = FixNodeName( cl.TargetNode()->Name() ); - - bone->mOffsetMatrix = cl.TransformLink(); - bone->mOffsetMatrix.Inverse(); - - bone->mOffsetMatrix = bone->mOffsetMatrix * node_global_transform; - - bone->mNumWeights = static_cast( out_indices.size() ); - aiVertexWeight* cursor = bone->mWeights = new aiVertexWeight[ out_indices.size() ]; - - const size_t no_index_sentinel = std::numeric_limits::max(); - const WeightArray& weights = cl.GetWeights(); - - const size_t c = index_out_indices.size(); - for ( size_t i = 0; i < c; ++i ) { - const size_t index_index = index_out_indices[ i ]; - - if ( index_index == no_index_sentinel ) { - continue; - } - - const size_t cc = count_out_indices[ i ]; - for ( size_t j = 0; j < cc; ++j ) { - aiVertexWeight& out_weight = *cursor++; - - out_weight.mVertexId = static_cast( out_indices[ index_index + j ] ); - out_weight.mWeight = weights[ i ]; - } - } -} - -void FBXConverter::ConvertMaterialForMesh( aiMesh* out, const Model& model, const MeshGeometry& geo, - MatIndexArray::value_type materialIndex ) -{ - // locate source materials for this mesh - const std::vector& mats = model.GetMaterials(); - if ( static_cast( materialIndex ) >= mats.size() || materialIndex < 0 ) { - FBXImporter::LogError( "material index out of bounds, setting default material" ); - out->mMaterialIndex = GetDefaultMaterial(); - return; - } - - const Material* const mat = mats[ materialIndex ]; - MaterialMap::const_iterator it = materials_converted.find( mat ); - if ( it != materials_converted.end() ) { - out->mMaterialIndex = ( *it ).second; - return; - } - - out->mMaterialIndex = ConvertMaterial( *mat, &geo ); - materials_converted[ mat ] = out->mMaterialIndex; -} - -unsigned int FBXConverter::GetDefaultMaterial() -{ - if ( defaultMaterialIndex ) { - return defaultMaterialIndex - 1; - } - - aiMaterial* out_mat = new aiMaterial(); - materials.push_back( out_mat ); - - const aiColor3D diffuse = aiColor3D( 0.8f, 0.8f, 0.8f ); - out_mat->AddProperty( &diffuse, 1, AI_MATKEY_COLOR_DIFFUSE ); - - aiString s; - s.Set( AI_DEFAULT_MATERIAL_NAME ); - - out_mat->AddProperty( &s, AI_MATKEY_NAME ); - - defaultMaterialIndex = static_cast< unsigned int >( materials.size() ); - return defaultMaterialIndex - 1; -} - - -unsigned int FBXConverter::ConvertMaterial( const Material& material, const MeshGeometry* const mesh ) -{ - const PropertyTable& props = material.Props(); - - // generate empty output material - aiMaterial* out_mat = new aiMaterial(); - materials_converted[ &material ] = static_cast( materials.size() ); - - materials.push_back( out_mat ); - - aiString str; - - // strip Material:: prefix - std::string name = material.Name(); - if ( name.substr( 0, 10 ) == "Material::" ) { - name = name.substr( 10 ); - } - - // set material name if not empty - this could happen - // and there should be no key for it in this case. - if ( name.length() ) { - str.Set( name ); - out_mat->AddProperty( &str, AI_MATKEY_NAME ); - } - - // shading stuff and colors - SetShadingPropertiesCommon( out_mat, props ); - - // texture assignments - SetTextureProperties( out_mat, material.Textures(), mesh ); - SetTextureProperties( out_mat, material.LayeredTextures(), mesh ); - - return static_cast( materials.size() - 1 ); -} - -unsigned int FBXConverter::ConvertVideo( const Video& video ) -{ - // generate empty output texture - aiTexture* out_tex = new aiTexture(); - textures.push_back( out_tex ); - - // assuming the texture is compressed - out_tex->mWidth = static_cast( video.ContentLength() ); // total data size - out_tex->mHeight = 0; // fixed to 0 - - // steal the data from the Video to avoid an additional copy - out_tex->pcData = reinterpret_cast( const_cast( video ).RelinquishContent() ); - - // try to extract a hint from the file extension - const std::string& filename = video.FileName().empty() ? video.RelativeFilename() : video.FileName(); - std::string ext = BaseImporter::GetExtension( filename ); - - if ( ext == "jpeg" ) { - ext = "jpg"; - } - - if ( ext.size() <= 3 ) { - memcpy( out_tex->achFormatHint, ext.c_str(), ext.size() ); - } - - out_tex->mFilename.Set(video.FileName().c_str()); - - return static_cast( textures.size() - 1 ); -} - -aiString FBXConverter::GetTexturePath(const Texture* tex) -{ - aiString path; - path.Set(tex->RelativeFilename()); - - const Video* media = tex->Media(); - if (media != nullptr) { - bool textureReady = false; //tells if our texture is ready (if it was loaded or if it was found) - unsigned int index; - - VideoMap::const_iterator it = textures_converted.find(media); - if (it != textures_converted.end()) { - index = (*it).second; - textureReady = true; - } - else { - if (media->ContentLength() > 0) { - index = ConvertVideo(*media); - textures_converted[media] = index; - textureReady = true; - } - } - - // setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture), if the texture is ready - if (doc.Settings().useLegacyEmbeddedTextureNaming) { - if (textureReady) { - // TODO: check the possibility of using the flag "AI_CONFIG_IMPORT_FBX_EMBEDDED_TEXTURES_LEGACY_NAMING" - // In FBX files textures are now stored internally by Assimp with their filename included - // Now Assimp can lookup through the loaded textures after all data is processed - // We need to load all textures before referencing them, as FBX file format order may reference a texture before loading it - // This may occur on this case too, it has to be studied - path.data[0] = '*'; - path.length = 1 + ASSIMP_itoa10(path.data + 1, MAXLEN - 1, index); - } - } - } - - return path; -} - -void FBXConverter::TrySetTextureProperties( aiMaterial* out_mat, const TextureMap& textures, - const std::string& propName, - aiTextureType target, const MeshGeometry* const mesh ) -{ - TextureMap::const_iterator it = textures.find( propName ); - if ( it == textures.end() ) { - return; - } - - const Texture* const tex = ( *it ).second; - if ( tex != 0 ) - { - aiString path = GetTexturePath(tex); - out_mat->AddProperty( &path, _AI_MATKEY_TEXTURE_BASE, target, 0 ); - - aiUVTransform uvTrafo; - // XXX handle all kinds of UV transformations - uvTrafo.mScaling = tex->UVScaling(); - uvTrafo.mTranslation = tex->UVTranslation(); - out_mat->AddProperty( &uvTrafo, 1, _AI_MATKEY_UVTRANSFORM_BASE, target, 0 ); - - const PropertyTable& props = tex->Props(); - - int uvIndex = 0; - - bool ok; - const std::string& uvSet = PropertyGet( props, "UVSet", ok ); - if ( ok ) { - // "default" is the name which usually appears in the FbxFileTexture template - if ( uvSet != "default" && uvSet.length() ) { - // this is a bit awkward - we need to find a mesh that uses this - // material and scan its UV channels for the given UV name because - // assimp references UV channels by index, not by name. - - // XXX: the case that UV channels may appear in different orders - // in meshes is unhandled. A possible solution would be to sort - // the UV channels alphabetically, but this would have the side - // effect that the primary (first) UV channel would sometimes - // be moved, causing trouble when users read only the first - // UV channel and ignore UV channel assignments altogether. - - const unsigned int matIndex = static_cast( std::distance( materials.begin(), - std::find( materials.begin(), materials.end(), out_mat ) - ) ); - - - uvIndex = -1; - if ( !mesh ) - { - for( const MeshMap::value_type& v : meshes_converted ) { - const MeshGeometry* const mesh = dynamic_cast ( v.first ); - if ( !mesh ) { - continue; - } - - const MatIndexArray& mats = mesh->GetMaterialIndices(); - if ( std::find( mats.begin(), mats.end(), matIndex ) == mats.end() ) { - continue; - } - - int index = -1; - for ( unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i ) { - if ( mesh->GetTextureCoords( i ).empty() ) { - break; - } - const std::string& name = mesh->GetTextureCoordChannelName( i ); - if ( name == uvSet ) { - index = static_cast( i ); - break; - } - } - if ( index == -1 ) { - FBXImporter::LogWarn( "did not find UV channel named " + uvSet + " in a mesh using this material" ); - continue; - } - - if ( uvIndex == -1 ) { - uvIndex = index; - } - else { - FBXImporter::LogWarn( "the UV channel named " + uvSet + - " appears at different positions in meshes, results will be wrong" ); - } - } - } - else - { - int index = -1; - for ( unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i ) { - if ( mesh->GetTextureCoords( i ).empty() ) { - break; - } - const std::string& name = mesh->GetTextureCoordChannelName( i ); - if ( name == uvSet ) { - index = static_cast( i ); - break; - } - } - if ( index == -1 ) { - FBXImporter::LogWarn( "did not find UV channel named " + uvSet + " in a mesh using this material" ); - } - - if ( uvIndex == -1 ) { - uvIndex = index; - } - } - - if ( uvIndex == -1 ) { - FBXImporter::LogWarn( "failed to resolve UV channel " + uvSet + ", using first UV channel" ); - uvIndex = 0; - } - } - } - - out_mat->AddProperty( &uvIndex, 1, _AI_MATKEY_UVWSRC_BASE, target, 0 ); - } -} - -void FBXConverter::TrySetTextureProperties( aiMaterial* out_mat, const LayeredTextureMap& layeredTextures, - const std::string& propName, - aiTextureType target, const MeshGeometry* const mesh ) { - LayeredTextureMap::const_iterator it = layeredTextures.find( propName ); - if ( it == layeredTextures.end() ) { - return; - } - - int texCount = (*it).second->textureCount(); - - // Set the blend mode for layered textures - int blendmode= (*it).second->GetBlendMode(); - out_mat->AddProperty(&blendmode,1,_AI_MATKEY_TEXOP_BASE,target,0); - - for(int texIndex = 0; texIndex < texCount; texIndex++){ - - const Texture* const tex = ( *it ).second->getTexture(texIndex); - - aiString path = GetTexturePath(tex); - out_mat->AddProperty( &path, _AI_MATKEY_TEXTURE_BASE, target, texIndex ); - - aiUVTransform uvTrafo; - // XXX handle all kinds of UV transformations - uvTrafo.mScaling = tex->UVScaling(); - uvTrafo.mTranslation = tex->UVTranslation(); - out_mat->AddProperty( &uvTrafo, 1, _AI_MATKEY_UVTRANSFORM_BASE, target, texIndex ); - - const PropertyTable& props = tex->Props(); - - int uvIndex = 0; - - bool ok; - const std::string& uvSet = PropertyGet( props, "UVSet", ok ); - if ( ok ) { - // "default" is the name which usually appears in the FbxFileTexture template - if ( uvSet != "default" && uvSet.length() ) { - // this is a bit awkward - we need to find a mesh that uses this - // material and scan its UV channels for the given UV name because - // assimp references UV channels by index, not by name. - - // XXX: the case that UV channels may appear in different orders - // in meshes is unhandled. A possible solution would be to sort - // the UV channels alphabetically, but this would have the side - // effect that the primary (first) UV channel would sometimes - // be moved, causing trouble when users read only the first - // UV channel and ignore UV channel assignments altogether. - - const unsigned int matIndex = static_cast( std::distance( materials.begin(), - std::find( materials.begin(), materials.end(), out_mat ) - ) ); - - uvIndex = -1; - if ( !mesh ) - { - for( const MeshMap::value_type& v : meshes_converted ) { - const MeshGeometry* const mesh = dynamic_cast ( v.first ); - if ( !mesh ) { - continue; - } - - const MatIndexArray& mats = mesh->GetMaterialIndices(); - if ( std::find( mats.begin(), mats.end(), matIndex ) == mats.end() ) { - continue; - } - - int index = -1; - for ( unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i ) { - if ( mesh->GetTextureCoords( i ).empty() ) { - break; - } - const std::string& name = mesh->GetTextureCoordChannelName( i ); - if ( name == uvSet ) { - index = static_cast( i ); - break; - } - } - if ( index == -1 ) { - FBXImporter::LogWarn( "did not find UV channel named " + uvSet + " in a mesh using this material" ); - continue; - } - - if ( uvIndex == -1 ) { - uvIndex = index; - } - else { - FBXImporter::LogWarn( "the UV channel named " + uvSet + - " appears at different positions in meshes, results will be wrong" ); - } - } - } - else - { - int index = -1; - for ( unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i ) { - if ( mesh->GetTextureCoords( i ).empty() ) { - break; - } - const std::string& name = mesh->GetTextureCoordChannelName( i ); - if ( name == uvSet ) { - index = static_cast( i ); - break; - } - } - if ( index == -1 ) { - FBXImporter::LogWarn( "did not find UV channel named " + uvSet + " in a mesh using this material" ); - } - - if ( uvIndex == -1 ) { - uvIndex = index; - } - } - - if ( uvIndex == -1 ) { - FBXImporter::LogWarn( "failed to resolve UV channel " + uvSet + ", using first UV channel" ); - uvIndex = 0; - } - } - } - - out_mat->AddProperty( &uvIndex, 1, _AI_MATKEY_UVWSRC_BASE, target, texIndex ); - } -} - -void FBXConverter::SetTextureProperties( aiMaterial* out_mat, const TextureMap& textures, const MeshGeometry* const mesh ) -{ - TrySetTextureProperties( out_mat, textures, "DiffuseColor", aiTextureType_DIFFUSE, mesh ); - TrySetTextureProperties( out_mat, textures, "AmbientColor", aiTextureType_AMBIENT, mesh ); - TrySetTextureProperties( out_mat, textures, "EmissiveColor", aiTextureType_EMISSIVE, mesh ); - TrySetTextureProperties( out_mat, textures, "SpecularColor", aiTextureType_SPECULAR, mesh ); - TrySetTextureProperties( out_mat, textures, "SpecularFactor", aiTextureType_SPECULAR, mesh); - TrySetTextureProperties( out_mat, textures, "TransparentColor", aiTextureType_OPACITY, mesh ); - TrySetTextureProperties( out_mat, textures, "ReflectionColor", aiTextureType_REFLECTION, mesh ); - TrySetTextureProperties( out_mat, textures, "DisplacementColor", aiTextureType_DISPLACEMENT, mesh ); - TrySetTextureProperties( out_mat, textures, "NormalMap", aiTextureType_NORMALS, mesh ); - TrySetTextureProperties( out_mat, textures, "Bump", aiTextureType_HEIGHT, mesh ); - TrySetTextureProperties( out_mat, textures, "ShininessExponent", aiTextureType_SHININESS, mesh ); -} - -void FBXConverter::SetTextureProperties( aiMaterial* out_mat, const LayeredTextureMap& layeredTextures, const MeshGeometry* const mesh ) -{ - TrySetTextureProperties( out_mat, layeredTextures, "DiffuseColor", aiTextureType_DIFFUSE, mesh ); - TrySetTextureProperties( out_mat, layeredTextures, "AmbientColor", aiTextureType_AMBIENT, mesh ); - TrySetTextureProperties( out_mat, layeredTextures, "EmissiveColor", aiTextureType_EMISSIVE, mesh ); - TrySetTextureProperties( out_mat, layeredTextures, "SpecularColor", aiTextureType_SPECULAR, mesh ); - TrySetTextureProperties( out_mat, layeredTextures, "SpecularFactor", aiTextureType_SPECULAR, mesh); - TrySetTextureProperties( out_mat, layeredTextures, "TransparentColor", aiTextureType_OPACITY, mesh ); - TrySetTextureProperties( out_mat, layeredTextures, "ReflectionColor", aiTextureType_REFLECTION, mesh ); - TrySetTextureProperties( out_mat, layeredTextures, "DisplacementColor", aiTextureType_DISPLACEMENT, mesh ); - TrySetTextureProperties( out_mat, layeredTextures, "NormalMap", aiTextureType_NORMALS, mesh ); - TrySetTextureProperties( out_mat, layeredTextures, "Bump", aiTextureType_HEIGHT, mesh ); - TrySetTextureProperties( out_mat, layeredTextures, "ShininessExponent", aiTextureType_SHININESS, mesh ); -} - -aiColor3D FBXConverter::GetColorPropertyFactored( const PropertyTable& props, const std::string& colorName, - const std::string& factorName, bool& result, bool useTemplate ) -{ - result = true; - - bool ok; - aiVector3D BaseColor = PropertyGet( props, colorName, ok, useTemplate ); - if ( ! ok ) { - result = false; - return aiColor3D( 0.0f, 0.0f, 0.0f ); - } - - // if no factor name, return the colour as is - if ( factorName.empty() ) { - return aiColor3D( BaseColor.x, BaseColor.y, BaseColor.z ); - } - - // otherwise it should be multiplied by the factor, if found. - float factor = PropertyGet( props, factorName, ok, useTemplate ); - if ( ok ) { - BaseColor *= factor; - } - return aiColor3D( BaseColor.x, BaseColor.y, BaseColor.z ); -} - -aiColor3D FBXConverter::GetColorPropertyFromMaterial( const PropertyTable& props, const std::string& baseName, - bool& result ) -{ - return GetColorPropertyFactored( props, baseName + "Color", baseName + "Factor", result, true ); -} - -aiColor3D FBXConverter::GetColorProperty( const PropertyTable& props, const std::string& colorName, - bool& result, bool useTemplate ) -{ - result = true; - bool ok; - const aiVector3D& ColorVec = PropertyGet( props, colorName, ok, useTemplate ); - if ( ! ok ) { - result = false; - return aiColor3D( 0.0f, 0.0f, 0.0f ); - } - return aiColor3D( ColorVec.x, ColorVec.y, ColorVec.z ); -} - -void FBXConverter::SetShadingPropertiesCommon( aiMaterial* out_mat, const PropertyTable& props ) -{ - // Set shading properties. - // Modern FBX Files have two separate systems for defining these, - // with only the more comprehensive one described in the property template. - // Likely the other values are a legacy system, - // which is still always exported by the official FBX SDK. - // - // Blender's FBX import and export mostly ignore this legacy system, - // and as we only support recent versions of FBX anyway, we can do the same. - bool ok; - - const aiColor3D& Diffuse = GetColorPropertyFromMaterial( props, "Diffuse", ok ); - if ( ok ) { - out_mat->AddProperty( &Diffuse, 1, AI_MATKEY_COLOR_DIFFUSE ); - } - - const aiColor3D& Emissive = GetColorPropertyFromMaterial( props, "Emissive", ok ); - if ( ok ) { - out_mat->AddProperty( &Emissive, 1, AI_MATKEY_COLOR_EMISSIVE ); - } - - const aiColor3D& Ambient = GetColorPropertyFromMaterial( props, "Ambient", ok ); - if ( ok ) { - out_mat->AddProperty( &Ambient, 1, AI_MATKEY_COLOR_AMBIENT ); - } - - // we store specular factor as SHININESS_STRENGTH, so just get the color - const aiColor3D& Specular = GetColorProperty( props, "SpecularColor", ok, true ); - if ( ok ) { - out_mat->AddProperty( &Specular, 1, AI_MATKEY_COLOR_SPECULAR ); - } - - // and also try to get SHININESS_STRENGTH - const float SpecularFactor = PropertyGet( props, "SpecularFactor", ok, true ); - if ( ok ) { - out_mat->AddProperty( &SpecularFactor, 1, AI_MATKEY_SHININESS_STRENGTH ); - } - - // and the specular exponent - const float ShininessExponent = PropertyGet( props, "ShininessExponent", ok ); - if ( ok ) { - out_mat->AddProperty( &ShininessExponent, 1, AI_MATKEY_SHININESS ); - } - - // TransparentColor / TransparencyFactor... gee thanks FBX :rolleyes: - const aiColor3D& Transparent = GetColorPropertyFactored( props, "TransparentColor", "TransparencyFactor", ok ); - float CalculatedOpacity = 1.0f; - if ( ok ) { - out_mat->AddProperty( &Transparent, 1, AI_MATKEY_COLOR_TRANSPARENT ); - // as calculated by FBX SDK 2017: - CalculatedOpacity = 1.0f - ((Transparent.r + Transparent.g + Transparent.b) / 3.0f); - } - - // use of TransparencyFactor is inconsistent. - // Maya always stores it as 1.0, - // so we can't use it to set AI_MATKEY_OPACITY. - // Blender is more sensible and stores it as the alpha value. - // However both the FBX SDK and Blender always write an additional - // legacy "Opacity" field, so we can try to use that. - // - // If we can't find it, - // we can fall back to the value which the FBX SDK calculates - // from transparency colour (RGB) and factor (F) as - // 1.0 - F*((R+G+B)/3). - // - // There's no consistent way to interpret this opacity value, - // so it's up to clients to do the correct thing. - const float Opacity = PropertyGet( props, "Opacity", ok ); - if ( ok ) { - out_mat->AddProperty( &Opacity, 1, AI_MATKEY_OPACITY ); - } - else if ( CalculatedOpacity != 1.0 ) { - out_mat->AddProperty( &CalculatedOpacity, 1, AI_MATKEY_OPACITY ); - } - - // reflection color and factor are stored separately - const aiColor3D& Reflection = GetColorProperty( props, "ReflectionColor", ok, true ); - if ( ok ) { - out_mat->AddProperty( &Reflection, 1, AI_MATKEY_COLOR_REFLECTIVE ); - } - - float ReflectionFactor = PropertyGet( props, "ReflectionFactor", ok, true ); - if ( ok ) { - out_mat->AddProperty( &ReflectionFactor, 1, AI_MATKEY_REFLECTIVITY ); - } - - const float BumpFactor = PropertyGet(props, "BumpFactor", ok); - if (ok) { - out_mat->AddProperty(&BumpFactor, 1, AI_MATKEY_BUMPSCALING); - } - - const float DispFactor = PropertyGet(props, "DisplacementFactor", ok); - if (ok) { - out_mat->AddProperty(&DispFactor, 1, "$mat.displacementscaling", 0, 0); - } -} - - -double FBXConverter::FrameRateToDouble( FileGlobalSettings::FrameRate fp, double customFPSVal ) { - switch ( fp ) { - case FileGlobalSettings::FrameRate_DEFAULT: - return 1.0; - - case FileGlobalSettings::FrameRate_120: - return 120.0; - - case FileGlobalSettings::FrameRate_100: - return 100.0; - - case FileGlobalSettings::FrameRate_60: - return 60.0; - - case FileGlobalSettings::FrameRate_50: - return 50.0; - - case FileGlobalSettings::FrameRate_48: - return 48.0; - - case FileGlobalSettings::FrameRate_30: - case FileGlobalSettings::FrameRate_30_DROP: - return 30.0; - - case FileGlobalSettings::FrameRate_NTSC_DROP_FRAME: - case FileGlobalSettings::FrameRate_NTSC_FULL_FRAME: - return 29.9700262; - - case FileGlobalSettings::FrameRate_PAL: - return 25.0; - - case FileGlobalSettings::FrameRate_CINEMA: - return 24.0; - - case FileGlobalSettings::FrameRate_1000: - return 1000.0; - - case FileGlobalSettings::FrameRate_CINEMA_ND: - return 23.976; - - case FileGlobalSettings::FrameRate_CUSTOM: - return customFPSVal; - - case FileGlobalSettings::FrameRate_MAX: // this is to silence compiler warnings - break; - } - - ai_assert( false ); - - return -1.0f; -} - - -void FBXConverter::ConvertAnimations() -{ - // first of all determine framerate - const FileGlobalSettings::FrameRate fps = doc.GlobalSettings().TimeMode(); - const float custom = doc.GlobalSettings().CustomFrameRate(); - anim_fps = FrameRateToDouble( fps, custom ); - - const std::vector& animations = doc.AnimationStacks(); - for( const AnimationStack* stack : animations ) { - ConvertAnimationStack( *stack ); - } -} - -std::string FBXConverter::FixNodeName( const std::string& name ) { - // strip Model:: prefix, avoiding ambiguities (i.e. don't strip if - // this causes ambiguities, well possible between empty identifiers, - // such as "Model::" and ""). Make sure the behaviour is consistent - // across multiple calls to FixNodeName(). - if ( name.substr( 0, 7 ) == "Model::" ) { - std::string temp = name.substr( 7 ); - return temp; - } - - return name; -} - -void FBXConverter::ConvertAnimationStack( const AnimationStack& st ) -{ - const AnimationLayerList& layers = st.Layers(); - if ( layers.empty() ) { - return; - } - - aiAnimation* const anim = new aiAnimation(); - animations.push_back( anim ); - - // strip AnimationStack:: prefix - std::string name = st.Name(); - if ( name.substr( 0, 16 ) == "AnimationStack::" ) { - name = name.substr( 16 ); - } - else if ( name.substr( 0, 11 ) == "AnimStack::" ) { - name = name.substr( 11 ); - } - - anim->mName.Set( name ); - - // need to find all nodes for which we need to generate node animations - - // it may happen that we need to merge multiple layers, though. - NodeMap node_map; - - // reverse mapping from curves to layers, much faster than querying - // the FBX DOM for it. - LayerMap layer_map; - - const char* prop_whitelist[] = { - "Lcl Scaling", - "Lcl Rotation", - "Lcl Translation" - }; - - for( const AnimationLayer* layer : layers ) { - ai_assert( layer ); - - const AnimationCurveNodeList& nodes = layer->Nodes( prop_whitelist, 3 ); - for( const AnimationCurveNode* node : nodes ) { - ai_assert( node ); - - const Model* const model = dynamic_cast( node->Target() ); - // this can happen - it could also be a NodeAttribute (i.e. for camera animations) - if ( !model ) { - continue; - } - - const std::string& name = FixNodeName( model->Name() ); - node_map[ name ].push_back( node ); - - layer_map[ node ] = layer; - } - } - - // generate node animations - std::vector node_anims; - - double min_time = 1e10; - double max_time = -1e10; - - int64_t start_time = st.LocalStart(); - int64_t stop_time = st.LocalStop(); - bool has_local_startstop = start_time != 0 || stop_time != 0; - if ( !has_local_startstop ) { - // no time range given, so accept every keyframe and use the actual min/max time - // the numbers are INT64_MIN/MAX, the 20000 is for safety because GenerateNodeAnimations uses an epsilon of 10000 - start_time = -9223372036854775807ll + 20000; - stop_time = 9223372036854775807ll - 20000; - } - - try { - for( const NodeMap::value_type& kv : node_map ) { - GenerateNodeAnimations( node_anims, - kv.first, - kv.second, - layer_map, - start_time, stop_time, - max_time, - min_time ); - } - } - catch ( std::exception& ) { - std::for_each( node_anims.begin(), node_anims.end(), Util::delete_fun() ); - throw; - } - - if ( node_anims.size() ) { - anim->mChannels = new aiNodeAnim*[ node_anims.size() ](); - anim->mNumChannels = static_cast( node_anims.size() ); - - std::swap_ranges( node_anims.begin(), node_anims.end(), anim->mChannels ); - } - else { - // empty animations would fail validation, so drop them - delete anim; - animations.pop_back(); - FBXImporter::LogInfo( "ignoring empty AnimationStack (using IK?): " + name ); - return; - } - - double start_time_fps = has_local_startstop ? (CONVERT_FBX_TIME(start_time) * anim_fps) : min_time; - double stop_time_fps = has_local_startstop ? (CONVERT_FBX_TIME(stop_time) * anim_fps) : max_time; - - // adjust relative timing for animation - for ( unsigned int c = 0; c < anim->mNumChannels; c++ ) { - aiNodeAnim* channel = anim->mChannels[ c ]; - for ( uint32_t i = 0; i < channel->mNumPositionKeys; i++ ) - channel->mPositionKeys[ i ].mTime -= start_time_fps; - for ( uint32_t i = 0; i < channel->mNumRotationKeys; i++ ) - channel->mRotationKeys[ i ].mTime -= start_time_fps; - for ( uint32_t i = 0; i < channel->mNumScalingKeys; i++ ) - channel->mScalingKeys[ i ].mTime -= start_time_fps; - } - - // for some mysterious reason, mDuration is simply the maximum key -- the - // validator always assumes animations to start at zero. - anim->mDuration = stop_time_fps - start_time_fps; - anim->mTicksPerSecond = anim_fps; -} - -#ifdef ASSIMP_BUILD_DEBUG -// ------------------------------------------------------------------------------------------------ -// sanity check whether the input is ok -static void validateAnimCurveNodes( const std::vector& curves, - bool strictMode ) { - const Object* target( NULL ); - for( const AnimationCurveNode* node : curves ) { - if ( !target ) { - target = node->Target(); - } - if ( node->Target() != target ) { - FBXImporter::LogWarn( "Node target is nullptr type." ); - } - if ( strictMode ) { - ai_assert( node->Target() == target ); - } - } -} -#endif // ASSIMP_BUILD_DEBUG - -// ------------------------------------------------------------------------------------------------ -void FBXConverter::GenerateNodeAnimations( std::vector& node_anims, - const std::string& fixed_name, - const std::vector& curves, - const LayerMap& layer_map, - int64_t start, int64_t stop, - double& max_time, - double& min_time ) -{ - - NodeMap node_property_map; - ai_assert( curves.size() ); - -#ifdef ASSIMP_BUILD_DEBUG - validateAnimCurveNodes( curves, doc.Settings().strictMode ); -#endif - const AnimationCurveNode* curve_node = NULL; - for( const AnimationCurveNode* node : curves ) { - ai_assert( node ); - - if ( node->TargetProperty().empty() ) { - FBXImporter::LogWarn( "target property for animation curve not set: " + node->Name() ); - continue; - } - - curve_node = node; - if ( node->Curves().empty() ) { - FBXImporter::LogWarn( "no animation curves assigned to AnimationCurveNode: " + node->Name() ); - continue; - } - - node_property_map[ node->TargetProperty() ].push_back( node ); - } - - ai_assert( curve_node ); - ai_assert( curve_node->TargetAsModel() ); - - const Model& target = *curve_node->TargetAsModel(); - - // check for all possible transformation components - NodeMap::const_iterator chain[ TransformationComp_MAXIMUM ]; - - bool has_any = false; - bool has_complex = false; - - for ( size_t i = 0; i < TransformationComp_MAXIMUM; ++i ) { - const TransformationComp comp = static_cast( i ); - - // inverse pivots don't exist in the input, we just generate them - if ( comp == TransformationComp_RotationPivotInverse || comp == TransformationComp_ScalingPivotInverse ) { - chain[ i ] = node_property_map.end(); - continue; - } - - chain[ i ] = node_property_map.find( NameTransformationCompProperty( comp ) ); - if ( chain[ i ] != node_property_map.end() ) { - - // check if this curves contains redundant information by looking - // up the corresponding node's transformation chain. - if ( doc.Settings().optimizeEmptyAnimationCurves && - IsRedundantAnimationData( target, comp, ( *chain[ i ] ).second ) ) { - - FBXImporter::LogDebug( "dropping redundant animation channel for node " + target.Name() ); - continue; - } - - has_any = true; - - if ( comp != TransformationComp_Rotation && comp != TransformationComp_Scaling && comp != TransformationComp_Translation ) - { - has_complex = true; - } - } - } - - if ( !has_any ) { - FBXImporter::LogWarn( "ignoring node animation, did not find any transformation key frames" ); - return; - } - - // this needs to play nicely with GenerateTransformationNodeChain() which will - // be invoked _later_ (animations come first). If this node has only rotation, - // scaling and translation _and_ there are no animated other components either, - // we can use a single node and also a single node animation channel. - if ( !has_complex && !NeedsComplexTransformationChain( target ) ) { - - aiNodeAnim* const nd = GenerateSimpleNodeAnim( fixed_name, target, chain, - node_property_map.end(), - layer_map, - start, stop, - max_time, - min_time, - true // input is TRS order, assimp is SRT - ); - - ai_assert( nd ); - if ( nd->mNumPositionKeys == 0 && nd->mNumRotationKeys == 0 && nd->mNumScalingKeys == 0 ) { - delete nd; - } - else { - node_anims.push_back( nd ); - } - return; - } - - // otherwise, things get gruesome and we need separate animation channels - // for each part of the transformation chain. Remember which channels - // we generated and pass this information to the node conversion - // code to avoid nodes that have identity transform, but non-identity - // animations, being dropped. - unsigned int flags = 0, bit = 0x1; - for ( size_t i = 0; i < TransformationComp_MAXIMUM; ++i, bit <<= 1 ) { - const TransformationComp comp = static_cast( i ); - - if ( chain[ i ] != node_property_map.end() ) { - flags |= bit; - - ai_assert( comp != TransformationComp_RotationPivotInverse ); - ai_assert( comp != TransformationComp_ScalingPivotInverse ); - - const std::string& chain_name = NameTransformationChainNode( fixed_name, comp ); - - aiNodeAnim* na = nullptr; - switch ( comp ) - { - case TransformationComp_Rotation: - case TransformationComp_PreRotation: - case TransformationComp_PostRotation: - case TransformationComp_GeometricRotation: - na = GenerateRotationNodeAnim( chain_name, - target, - ( *chain[ i ] ).second, - layer_map, - start, stop, - max_time, - min_time ); - - break; - - case TransformationComp_RotationOffset: - case TransformationComp_RotationPivot: - case TransformationComp_ScalingOffset: - case TransformationComp_ScalingPivot: - case TransformationComp_Translation: - case TransformationComp_GeometricTranslation: - na = GenerateTranslationNodeAnim( chain_name, - target, - ( *chain[ i ] ).second, - layer_map, - start, stop, - max_time, - min_time ); - - // pivoting requires us to generate an implicit inverse channel to undo the pivot translation - if ( comp == TransformationComp_RotationPivot ) { - const std::string& invName = NameTransformationChainNode( fixed_name, - TransformationComp_RotationPivotInverse ); - - aiNodeAnim* const inv = GenerateTranslationNodeAnim( invName, - target, - ( *chain[ i ] ).second, - layer_map, - start, stop, - max_time, - min_time, - true ); - - ai_assert( inv ); - if ( inv->mNumPositionKeys == 0 && inv->mNumRotationKeys == 0 && inv->mNumScalingKeys == 0 ) { - delete inv; - } - else { - node_anims.push_back( inv ); - } - - ai_assert( TransformationComp_RotationPivotInverse > i ); - flags |= bit << ( TransformationComp_RotationPivotInverse - i ); - } - else if ( comp == TransformationComp_ScalingPivot ) { - const std::string& invName = NameTransformationChainNode( fixed_name, - TransformationComp_ScalingPivotInverse ); - - aiNodeAnim* const inv = GenerateTranslationNodeAnim( invName, - target, - ( *chain[ i ] ).second, - layer_map, - start, stop, - max_time, - min_time, - true ); - - ai_assert( inv ); - if ( inv->mNumPositionKeys == 0 && inv->mNumRotationKeys == 0 && inv->mNumScalingKeys == 0 ) { - delete inv; - } - else { - node_anims.push_back( inv ); - } - - ai_assert( TransformationComp_RotationPivotInverse > i ); - flags |= bit << ( TransformationComp_RotationPivotInverse - i ); - } - - break; - - case TransformationComp_Scaling: - case TransformationComp_GeometricScaling: - na = GenerateScalingNodeAnim( chain_name, - target, - ( *chain[ i ] ).second, - layer_map, - start, stop, - max_time, - min_time ); - - break; - - default: - ai_assert( false ); - } - - ai_assert( na ); - if ( na->mNumPositionKeys == 0 && na->mNumRotationKeys == 0 && na->mNumScalingKeys == 0 ) { - delete na; - } - else { - node_anims.push_back( na ); - } - continue; - } - } - - node_anim_chain_bits[ fixed_name ] = flags; -} - -bool FBXConverter::IsRedundantAnimationData( const Model& target, - TransformationComp comp, - const std::vector& curves ) { - ai_assert( curves.size() ); - - // look for animation nodes with - // * sub channels for all relevant components set - // * one key/value pair per component - // * combined values match up the corresponding value in the bind pose node transformation - // only such nodes are 'redundant' for this function. - - if ( curves.size() > 1 ) { - return false; - } - - const AnimationCurveNode& nd = *curves.front(); - const AnimationCurveMap& sub_curves = nd.Curves(); - - const AnimationCurveMap::const_iterator dx = sub_curves.find( "d|X" ); - const AnimationCurveMap::const_iterator dy = sub_curves.find( "d|Y" ); - const AnimationCurveMap::const_iterator dz = sub_curves.find( "d|Z" ); - - if ( dx == sub_curves.end() || dy == sub_curves.end() || dz == sub_curves.end() ) { - return false; - } - - const KeyValueList& vx = ( *dx ).second->GetValues(); - const KeyValueList& vy = ( *dy ).second->GetValues(); - const KeyValueList& vz = ( *dz ).second->GetValues(); - - if ( vx.size() != 1 || vy.size() != 1 || vz.size() != 1 ) { - return false; - } - - const aiVector3D dyn_val = aiVector3D( vx[ 0 ], vy[ 0 ], vz[ 0 ] ); - const aiVector3D& static_val = PropertyGet( target.Props(), - NameTransformationCompProperty( comp ), - TransformationCompDefaultValue( comp ) - ); - - const float epsilon = 1e-6f; - return ( dyn_val - static_val ).SquareLength() < epsilon; -} - - -aiNodeAnim* FBXConverter::GenerateRotationNodeAnim( const std::string& name, - const Model& target, - const std::vector& curves, - const LayerMap& layer_map, - int64_t start, int64_t stop, - double& max_time, - double& min_time ) -{ - std::unique_ptr na( new aiNodeAnim() ); - na->mNodeName.Set( name ); - - ConvertRotationKeys( na.get(), curves, layer_map, start, stop, max_time, min_time, target.RotationOrder() ); - - // dummy scaling key - na->mScalingKeys = new aiVectorKey[ 1 ]; - na->mNumScalingKeys = 1; - - na->mScalingKeys[ 0 ].mTime = 0.; - na->mScalingKeys[ 0 ].mValue = aiVector3D( 1.0f, 1.0f, 1.0f ); - - // dummy position key - na->mPositionKeys = new aiVectorKey[ 1 ]; - na->mNumPositionKeys = 1; - - na->mPositionKeys[ 0 ].mTime = 0.; - na->mPositionKeys[ 0 ].mValue = aiVector3D(); - - return na.release(); -} - -aiNodeAnim* FBXConverter::GenerateScalingNodeAnim( const std::string& name, - const Model& /*target*/, - const std::vector& curves, - const LayerMap& layer_map, - int64_t start, int64_t stop, - double& max_time, - double& min_time ) -{ - std::unique_ptr na( new aiNodeAnim() ); - na->mNodeName.Set( name ); - - ConvertScaleKeys( na.get(), curves, layer_map, start, stop, max_time, min_time ); - - // dummy rotation key - na->mRotationKeys = new aiQuatKey[ 1 ]; - na->mNumRotationKeys = 1; - - na->mRotationKeys[ 0 ].mTime = 0.; - na->mRotationKeys[ 0 ].mValue = aiQuaternion(); - - // dummy position key - na->mPositionKeys = new aiVectorKey[ 1 ]; - na->mNumPositionKeys = 1; - - na->mPositionKeys[ 0 ].mTime = 0.; - na->mPositionKeys[ 0 ].mValue = aiVector3D(); - - return na.release(); -} - -aiNodeAnim* FBXConverter::GenerateTranslationNodeAnim( const std::string& name, - const Model& /*target*/, - const std::vector& curves, - const LayerMap& layer_map, - int64_t start, int64_t stop, - double& max_time, - double& min_time, - bool inverse ) { - std::unique_ptr na( new aiNodeAnim() ); - na->mNodeName.Set( name ); - - ConvertTranslationKeys( na.get(), curves, layer_map, start, stop, max_time, min_time ); - - if ( inverse ) { - for ( unsigned int i = 0; i < na->mNumPositionKeys; ++i ) { - na->mPositionKeys[ i ].mValue *= -1.0f; - } - } - - // dummy scaling key - na->mScalingKeys = new aiVectorKey[ 1 ]; - na->mNumScalingKeys = 1; - - na->mScalingKeys[ 0 ].mTime = 0.; - na->mScalingKeys[ 0 ].mValue = aiVector3D( 1.0f, 1.0f, 1.0f ); - - // dummy rotation key - na->mRotationKeys = new aiQuatKey[ 1 ]; - na->mNumRotationKeys = 1; - - na->mRotationKeys[ 0 ].mTime = 0.; - na->mRotationKeys[ 0 ].mValue = aiQuaternion(); - - return na.release(); -} - -aiNodeAnim* FBXConverter::GenerateSimpleNodeAnim( const std::string& name, - const Model& target, - NodeMap::const_iterator chain[ TransformationComp_MAXIMUM ], - NodeMap::const_iterator iter_end, - const LayerMap& layer_map, - int64_t start, int64_t stop, - double& max_time, - double& min_time, - bool reverse_order ) - -{ - std::unique_ptr na( new aiNodeAnim() ); - na->mNodeName.Set( name ); - - const PropertyTable& props = target.Props(); - - // need to convert from TRS order to SRT? - if ( reverse_order ) { - - aiVector3D def_scale = PropertyGet( props, "Lcl Scaling", aiVector3D( 1.f, 1.f, 1.f ) ); - aiVector3D def_translate = PropertyGet( props, "Lcl Translation", aiVector3D( 0.f, 0.f, 0.f ) ); - aiVector3D def_rot = PropertyGet( props, "Lcl Rotation", aiVector3D( 0.f, 0.f, 0.f ) ); - - KeyFrameListList scaling; - KeyFrameListList translation; - KeyFrameListList rotation; - - if ( chain[ TransformationComp_Scaling ] != iter_end ) { - scaling = GetKeyframeList( ( *chain[ TransformationComp_Scaling ] ).second, start, stop ); - } - - if ( chain[ TransformationComp_Translation ] != iter_end ) { - translation = GetKeyframeList( ( *chain[ TransformationComp_Translation ] ).second, start, stop ); - } - - if ( chain[ TransformationComp_Rotation ] != iter_end ) { - rotation = GetKeyframeList( ( *chain[ TransformationComp_Rotation ] ).second, start, stop ); - } - - KeyFrameListList joined; - joined.insert( joined.end(), scaling.begin(), scaling.end() ); - joined.insert( joined.end(), translation.begin(), translation.end() ); - joined.insert( joined.end(), rotation.begin(), rotation.end() ); - - const KeyTimeList& times = GetKeyTimeList( joined ); - - aiQuatKey* out_quat = new aiQuatKey[ times.size() ]; - aiVectorKey* out_scale = new aiVectorKey[ times.size() ]; - aiVectorKey* out_translation = new aiVectorKey[ times.size() ]; - - if ( times.size() ) - { - ConvertTransformOrder_TRStoSRT( out_quat, out_scale, out_translation, - scaling, - translation, - rotation, - times, - max_time, - min_time, - target.RotationOrder(), - def_scale, - def_translate, - def_rot ); - } - - // XXX remove duplicates / redundant keys which this operation did - // likely produce if not all three channels were equally dense. - - na->mNumScalingKeys = static_cast( times.size() ); - na->mNumRotationKeys = na->mNumScalingKeys; - na->mNumPositionKeys = na->mNumScalingKeys; - - na->mScalingKeys = out_scale; - na->mRotationKeys = out_quat; - na->mPositionKeys = out_translation; - } - else { - - // if a particular transformation is not given, grab it from - // the corresponding node to meet the semantics of aiNodeAnim, - // which requires all of rotation, scaling and translation - // to be set. - if ( chain[ TransformationComp_Scaling ] != iter_end ) { - ConvertScaleKeys( na.get(), ( *chain[ TransformationComp_Scaling ] ).second, - layer_map, - start, stop, - max_time, - min_time ); - } - else { - na->mScalingKeys = new aiVectorKey[ 1 ]; - na->mNumScalingKeys = 1; - - na->mScalingKeys[ 0 ].mTime = 0.; - na->mScalingKeys[ 0 ].mValue = PropertyGet( props, "Lcl Scaling", - aiVector3D( 1.f, 1.f, 1.f ) ); - } - - if ( chain[ TransformationComp_Rotation ] != iter_end ) { - ConvertRotationKeys( na.get(), ( *chain[ TransformationComp_Rotation ] ).second, - layer_map, - start, stop, - max_time, - min_time, - target.RotationOrder() ); - } - else { - na->mRotationKeys = new aiQuatKey[ 1 ]; - na->mNumRotationKeys = 1; - - na->mRotationKeys[ 0 ].mTime = 0.; - na->mRotationKeys[ 0 ].mValue = EulerToQuaternion( - PropertyGet( props, "Lcl Rotation", aiVector3D( 0.f, 0.f, 0.f ) ), - target.RotationOrder() ); - } - - if ( chain[ TransformationComp_Translation ] != iter_end ) { - ConvertTranslationKeys( na.get(), ( *chain[ TransformationComp_Translation ] ).second, - layer_map, - start, stop, - max_time, - min_time ); - } - else { - na->mPositionKeys = new aiVectorKey[ 1 ]; - na->mNumPositionKeys = 1; - - na->mPositionKeys[ 0 ].mTime = 0.; - na->mPositionKeys[ 0 ].mValue = PropertyGet( props, "Lcl Translation", - aiVector3D( 0.f, 0.f, 0.f ) ); - } - - } - return na.release(); -} - -FBXConverter::KeyFrameListList FBXConverter::GetKeyframeList( const std::vector& nodes, int64_t start, int64_t stop ) -{ - KeyFrameListList inputs; - inputs.reserve( nodes.size() * 3 ); - - //give some breathing room for rounding errors - int64_t adj_start = start - 10000; - int64_t adj_stop = stop + 10000; - - for( const AnimationCurveNode* node : nodes ) { - ai_assert( node ); - - const AnimationCurveMap& curves = node->Curves(); - for( const AnimationCurveMap::value_type& kv : curves ) { - - unsigned int mapto; - if ( kv.first == "d|X" ) { - mapto = 0; - } - else if ( kv.first == "d|Y" ) { - mapto = 1; - } - else if ( kv.first == "d|Z" ) { - mapto = 2; - } - else { - FBXImporter::LogWarn( "ignoring scale animation curve, did not recognize target component" ); - continue; - } - - const AnimationCurve* const curve = kv.second; - ai_assert( curve->GetKeys().size() == curve->GetValues().size() && curve->GetKeys().size() ); - - //get values within the start/stop time window - std::shared_ptr Keys( new KeyTimeList() ); - std::shared_ptr Values( new KeyValueList() ); - const size_t count = curve->GetKeys().size(); - Keys->reserve( count ); - Values->reserve( count ); - for (size_t n = 0; n < count; n++ ) - { - int64_t k = curve->GetKeys().at( n ); - if ( k >= adj_start && k <= adj_stop ) - { - Keys->push_back( k ); - Values->push_back( curve->GetValues().at( n ) ); - } - } - - inputs.push_back( std::make_tuple( Keys, Values, mapto ) ); - } - } - return inputs; // pray for NRVO :-) -} - - -KeyTimeList FBXConverter::GetKeyTimeList( const KeyFrameListList& inputs ) { - ai_assert( !inputs.empty() ); - - // reserve some space upfront - it is likely that the key-frame lists - // have matching time values, so max(of all key-frame lists) should - // be a good estimate. - KeyTimeList keys; - - size_t estimate = 0; - for( const KeyFrameList& kfl : inputs ) { - estimate = std::max( estimate, std::get<0>(kfl)->size() ); - } - - keys.reserve( estimate ); - - std::vector next_pos; - next_pos.resize( inputs.size(), 0 ); - - const size_t count = inputs.size(); - while ( true ) { - - int64_t min_tick = std::numeric_limits::max(); - for ( size_t i = 0; i < count; ++i ) { - const KeyFrameList& kfl = inputs[ i ]; - - if ( std::get<0>(kfl)->size() > next_pos[ i ] && std::get<0>(kfl)->at( next_pos[ i ] ) < min_tick ) { - min_tick = std::get<0>(kfl)->at( next_pos[ i ] ); - } - } - - if ( min_tick == std::numeric_limits::max() ) { - break; - } - keys.push_back( min_tick ); - - for ( size_t i = 0; i < count; ++i ) { - const KeyFrameList& kfl = inputs[ i ]; - - - while ( std::get<0>(kfl)->size() > next_pos[ i ] && std::get<0>(kfl)->at( next_pos[ i ] ) == min_tick ) { - ++next_pos[ i ]; - } - } - } - - return keys; -} - -void FBXConverter::InterpolateKeys( aiVectorKey* valOut, const KeyTimeList& keys, const KeyFrameListList& inputs, - const aiVector3D& def_value, - double& max_time, - double& min_time ) { - ai_assert( !keys.empty() ); - ai_assert( nullptr != valOut ); - - std::vector next_pos; - const size_t count( inputs.size() ); - - next_pos.resize( inputs.size(), 0 ); - - for( KeyTimeList::value_type time : keys ) { - ai_real result[ 3 ] = { def_value.x, def_value.y, def_value.z }; - - for ( size_t i = 0; i < count; ++i ) { - const KeyFrameList& kfl = inputs[ i ]; - - const size_t ksize = std::get<0>(kfl)->size(); - if (ksize == 0) { - continue; - } - if ( ksize > next_pos[ i ] && std::get<0>(kfl)->at( next_pos[ i ] ) == time ) { - ++next_pos[ i ]; - } - - const size_t id0 = next_pos[ i ]>0 ? next_pos[ i ] - 1 : 0; - const size_t id1 = next_pos[ i ] == ksize ? ksize - 1 : next_pos[ i ]; - - // use lerp for interpolation - const KeyValueList::value_type valueA = std::get<1>(kfl)->at( id0 ); - const KeyValueList::value_type valueB = std::get<1>(kfl)->at( id1 ); - - const KeyTimeList::value_type timeA = std::get<0>(kfl)->at( id0 ); - const KeyTimeList::value_type timeB = std::get<0>(kfl)->at( id1 ); - - const ai_real factor = timeB == timeA ? ai_real(0.) : static_cast( ( time - timeA ) ) / ( timeB - timeA ); - const ai_real interpValue = static_cast( valueA + ( valueB - valueA ) * factor ); - - result[ std::get<2>(kfl) ] = interpValue; - } - - // magic value to convert fbx times to seconds - valOut->mTime = CONVERT_FBX_TIME( time ) * anim_fps; - - min_time = std::min( min_time, valOut->mTime ); - max_time = std::max( max_time, valOut->mTime ); - - valOut->mValue.x = result[ 0 ]; - valOut->mValue.y = result[ 1 ]; - valOut->mValue.z = result[ 2 ]; - - ++valOut; - } -} - -void FBXConverter::InterpolateKeys( aiQuatKey* valOut, const KeyTimeList& keys, const KeyFrameListList& inputs, - const aiVector3D& def_value, - double& maxTime, - double& minTime, - Model::RotOrder order ) -{ - ai_assert( !keys.empty() ); - ai_assert( nullptr != valOut ); - - std::unique_ptr temp( new aiVectorKey[ keys.size() ] ); - InterpolateKeys( temp.get(), keys, inputs, def_value, maxTime, minTime ); - - aiMatrix4x4 m; - - aiQuaternion lastq; - - for ( size_t i = 0, c = keys.size(); i < c; ++i ) { - - valOut[ i ].mTime = temp[ i ].mTime; - - GetRotationMatrix( order, temp[ i ].mValue, m ); - aiQuaternion quat = aiQuaternion( aiMatrix3x3( m ) ); - - // take shortest path by checking the inner product - // http://www.3dkingdoms.com/weekly/weekly.php?a=36 - if ( quat.x * lastq.x + quat.y * lastq.y + quat.z * lastq.z + quat.w * lastq.w < 0 ) - { - quat.x = -quat.x; - quat.y = -quat.y; - quat.z = -quat.z; - quat.w = -quat.w; - } - lastq = quat; - - valOut[ i ].mValue = quat; - } -} - -void FBXConverter::ConvertTransformOrder_TRStoSRT( aiQuatKey* out_quat, aiVectorKey* out_scale, - aiVectorKey* out_translation, - const KeyFrameListList& scaling, - const KeyFrameListList& translation, - const KeyFrameListList& rotation, - const KeyTimeList& times, - double& maxTime, - double& minTime, - Model::RotOrder order, - const aiVector3D& def_scale, - const aiVector3D& def_translate, - const aiVector3D& def_rotation ) -{ - if ( rotation.size() ) { - InterpolateKeys( out_quat, times, rotation, def_rotation, maxTime, minTime, order ); - } - else { - for ( size_t i = 0; i < times.size(); ++i ) { - out_quat[ i ].mTime = CONVERT_FBX_TIME( times[ i ] ) * anim_fps; - out_quat[ i ].mValue = EulerToQuaternion( def_rotation, order ); - } - } - - if ( scaling.size() ) { - InterpolateKeys( out_scale, times, scaling, def_scale, maxTime, minTime ); - } - else { - for ( size_t i = 0; i < times.size(); ++i ) { - out_scale[ i ].mTime = CONVERT_FBX_TIME( times[ i ] ) * anim_fps; - out_scale[ i ].mValue = def_scale; - } - } - - if ( translation.size() ) { - InterpolateKeys( out_translation, times, translation, def_translate, maxTime, minTime ); - } - else { - for ( size_t i = 0; i < times.size(); ++i ) { - out_translation[ i ].mTime = CONVERT_FBX_TIME( times[ i ] ) * anim_fps; - out_translation[ i ].mValue = def_translate; - } - } - - const size_t count = times.size(); - for ( size_t i = 0; i < count; ++i ) { - aiQuaternion& r = out_quat[ i ].mValue; - aiVector3D& s = out_scale[ i ].mValue; - aiVector3D& t = out_translation[ i ].mValue; - - aiMatrix4x4 mat, temp; - aiMatrix4x4::Translation( t, mat ); - mat *= aiMatrix4x4( r.GetMatrix() ); - mat *= aiMatrix4x4::Scaling( s, temp ); - - mat.Decompose( s, r, t ); - } -} - -aiQuaternion FBXConverter::EulerToQuaternion( const aiVector3D& rot, Model::RotOrder order ) -{ - aiMatrix4x4 m; - GetRotationMatrix( order, rot, m ); - - return aiQuaternion( aiMatrix3x3( m ) ); -} - -void FBXConverter::ConvertScaleKeys( aiNodeAnim* na, const std::vector& nodes, const LayerMap& /*layers*/, - int64_t start, int64_t stop, - double& maxTime, - double& minTime ) -{ - ai_assert( nodes.size() ); - - // XXX for now, assume scale should be blended geometrically (i.e. two - // layers should be multiplied with each other). There is a FBX - // property in the layer to specify the behaviour, though. - - const KeyFrameListList& inputs = GetKeyframeList( nodes, start, stop ); - const KeyTimeList& keys = GetKeyTimeList( inputs ); - - na->mNumScalingKeys = static_cast( keys.size() ); - na->mScalingKeys = new aiVectorKey[ keys.size() ]; - if ( keys.size() > 0 ) - InterpolateKeys( na->mScalingKeys, keys, inputs, aiVector3D( 1.0f, 1.0f, 1.0f ), maxTime, minTime ); -} - -void FBXConverter::ConvertTranslationKeys( aiNodeAnim* na, const std::vector& nodes, - const LayerMap& /*layers*/, - int64_t start, int64_t stop, - double& maxTime, - double& minTime ) -{ - ai_assert( nodes.size() ); - - // XXX see notes in ConvertScaleKeys() - const KeyFrameListList& inputs = GetKeyframeList( nodes, start, stop ); - const KeyTimeList& keys = GetKeyTimeList( inputs ); - - na->mNumPositionKeys = static_cast( keys.size() ); - na->mPositionKeys = new aiVectorKey[ keys.size() ]; - if ( keys.size() > 0 ) - InterpolateKeys( na->mPositionKeys, keys, inputs, aiVector3D( 0.0f, 0.0f, 0.0f ), maxTime, minTime ); -} - -void FBXConverter::ConvertRotationKeys( aiNodeAnim* na, const std::vector& nodes, - const LayerMap& /*layers*/, - int64_t start, int64_t stop, - double& maxTime, - double& minTime, - Model::RotOrder order ) -{ - ai_assert( nodes.size() ); - - // XXX see notes in ConvertScaleKeys() - const std::vector< KeyFrameList >& inputs = GetKeyframeList( nodes, start, stop ); - const KeyTimeList& keys = GetKeyTimeList( inputs ); - - na->mNumRotationKeys = static_cast( keys.size() ); - na->mRotationKeys = new aiQuatKey[ keys.size() ]; - if (!keys.empty()) { - InterpolateKeys(na->mRotationKeys, keys, inputs, aiVector3D(0.0f, 0.0f, 0.0f), maxTime, minTime, order); - } -} - -void FBXConverter::ConvertGlobalSettings() { - if (nullptr == out) { - return; - } - - out->mMetaData = aiMetadata::Alloc(1); - unsigned int index(0); - const double unitScalFactor(doc.GlobalSettings().UnitScaleFactor()); - out->mMetaData->Set(index, "UnitScaleFactor", unitScalFactor); -} - -void FBXConverter::TransferDataToScene() -{ - ai_assert( !out->mMeshes ); - ai_assert( !out->mNumMeshes ); - - // note: the trailing () ensures initialization with NULL - not - // many C++ users seem to know this, so pointing it out to avoid - // confusion why this code works. - - if ( meshes.size() ) { - out->mMeshes = new aiMesh*[ meshes.size() ](); - out->mNumMeshes = static_cast( meshes.size() ); - - std::swap_ranges( meshes.begin(), meshes.end(), out->mMeshes ); - } - - if ( materials.size() ) { - out->mMaterials = new aiMaterial*[ materials.size() ](); - out->mNumMaterials = static_cast( materials.size() ); - - std::swap_ranges( materials.begin(), materials.end(), out->mMaterials ); - } - - if ( animations.size() ) { - out->mAnimations = new aiAnimation*[ animations.size() ](); - out->mNumAnimations = static_cast( animations.size() ); - - std::swap_ranges( animations.begin(), animations.end(), out->mAnimations ); - } - - if ( lights.size() ) { - out->mLights = new aiLight*[ lights.size() ](); - out->mNumLights = static_cast( lights.size() ); - - std::swap_ranges( lights.begin(), lights.end(), out->mLights ); - } - - if ( cameras.size() ) { - out->mCameras = new aiCamera*[ cameras.size() ](); - out->mNumCameras = static_cast( cameras.size() ); - - std::swap_ranges( cameras.begin(), cameras.end(), out->mCameras ); - } - - if ( textures.size() ) { - out->mTextures = new aiTexture*[ textures.size() ](); - out->mNumTextures = static_cast( textures.size() ); - - std::swap_ranges( textures.begin(), textures.end(), out->mTextures ); - } -} - -// ------------------------------------------------------------------------------------------------ -void ConvertToAssimpScene(aiScene* out, const Document& doc) -{ - FBXConverter converter(out,doc); -} - -} // !FBX -} // !Assimp - -#endif diff --git a/third_party/libassimp/code/FBXUtil.cpp b/third_party/libassimp/code/FBXUtil.cpp deleted file mode 100644 index 992c30efcf..0000000000 --- a/third_party/libassimp/code/FBXUtil.cpp +++ /dev/null @@ -1,120 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2018, 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 FBXUtil.cpp - * @brief Implementation of internal FBX utility functions - */ - -#include "FBXUtil.h" -#include "FBXTokenizer.h" - -#include -#include - -#ifndef ASSIMP_BUILD_NO_FBX_IMPORTER - -namespace Assimp { -namespace FBX { -namespace Util { - -// ------------------------------------------------------------------------------------------------ -const char* TokenTypeString(TokenType t) -{ - switch(t) { - case TokenType_OPEN_BRACKET: - return "TOK_OPEN_BRACKET"; - - case TokenType_CLOSE_BRACKET: - return "TOK_CLOSE_BRACKET"; - - case TokenType_DATA: - return "TOK_DATA"; - - case TokenType_COMMA: - return "TOK_COMMA"; - - case TokenType_KEY: - return "TOK_KEY"; - - case TokenType_BINARY_DATA: - return "TOK_BINARY_DATA"; - } - - ai_assert(false); - return ""; -} - - -// ------------------------------------------------------------------------------------------------ -std::string AddOffset(const std::string& prefix, const std::string& text, unsigned int offset) -{ - return static_cast( (Formatter::format() << prefix << " (offset 0x" << std::hex << offset << ") " << text) ); -} - -// ------------------------------------------------------------------------------------------------ -std::string AddLineAndColumn(const std::string& prefix, const std::string& text, unsigned int line, unsigned int column) -{ - return static_cast( (Formatter::format() << prefix << " (line " << line << " << col " << column << ") " << text) ); -} - -// ------------------------------------------------------------------------------------------------ -std::string AddTokenText(const std::string& prefix, const std::string& text, const Token* tok) -{ - if(tok->IsBinary()) { - return static_cast( (Formatter::format() << prefix << - " (" << TokenTypeString(tok->Type()) << - ", offset 0x" << std::hex << tok->Offset() << ") " << - text) ); - } - - return static_cast( (Formatter::format() << prefix << - " (" << TokenTypeString(tok->Type()) << - ", line " << tok->Line() << - ", col " << tok->Column() << ") " << - text) ); -} - -} // !Util -} // !FBX -} // !Assimp - -#endif diff --git a/third_party/libassimp/code/HMPFileData.h b/third_party/libassimp/code/HMP/HMPFileData.h similarity index 99% rename from third_party/libassimp/code/HMPFileData.h rename to third_party/libassimp/code/HMP/HMPFileData.h index 962f2f9c75..ab4100174b 100644 --- a/third_party/libassimp/code/HMPFileData.h +++ b/third_party/libassimp/code/HMP/HMPFileData.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/HMPLoader.cpp b/third_party/libassimp/code/HMP/HMPLoader.cpp similarity index 99% rename from third_party/libassimp/code/HMPLoader.cpp rename to third_party/libassimp/code/HMP/HMPLoader.cpp index 7f53f9b545..d5469181e4 100644 --- a/third_party/libassimp/code/HMPLoader.cpp +++ b/third_party/libassimp/code/HMP/HMPLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -47,14 +47,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_HMP_IMPORTER // internal headers -#include "HMPLoader.h" -#include "MD2FileData.h" -#include +#include "HMP/HMPLoader.h" +#include "MD2/MD2FileData.h" + #include #include #include #include +#include + using namespace Assimp; static const aiImporterDesc desc = { diff --git a/third_party/libassimp/code/HMPLoader.h b/third_party/libassimp/code/HMP/HMPLoader.h similarity index 98% rename from third_party/libassimp/code/HMPLoader.h rename to third_party/libassimp/code/HMP/HMPLoader.h index 4e513aee6f..421826c91e 100644 --- a/third_party/libassimp/code/HMPLoader.h +++ b/third_party/libassimp/code/HMP/HMPLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -48,8 +48,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // internal headers #include -#include "MDLLoader.h" -#include "HMPFileData.h" + +#include "MDL/MDLLoader.h" +#include "HMP/HMPFileData.h" namespace Assimp { using namespace HMP; diff --git a/third_party/libassimp/code/HalfLifeFileData.h b/third_party/libassimp/code/HMP/HalfLifeFileData.h similarity index 99% rename from third_party/libassimp/code/HalfLifeFileData.h rename to third_party/libassimp/code/HMP/HalfLifeFileData.h index 7c55657d40..ef328edf83 100644 --- a/third_party/libassimp/code/HalfLifeFileData.h +++ b/third_party/libassimp/code/HMP/HalfLifeFileData.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/Importer/IFC/IFCBoolean.cpp b/third_party/libassimp/code/Importer/IFC/IFCBoolean.cpp index 337e1d40b0..10e7bf3afb 100644 --- a/third_party/libassimp/code/Importer/IFC/IFCBoolean.cpp +++ b/third_party/libassimp/code/Importer/IFC/IFCBoolean.cpp @@ -44,8 +44,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_IFC_IMPORTER #include "code/Importer/IFC/IFCUtil.h" -#include "code/PolyTools.h" -#include "code/ProcessHelper.h" +#include "code/Common/PolyTools.h" +#include "code/PostProcessing/ProcessHelper.h" #include #include @@ -256,7 +256,7 @@ bool IntersectsBoundaryProfile(const IfcVector3& e0, const IfcVector3& e1, const for( size_t i = 0, bcount = boundary.size(); i < bcount; ++i ) { IfcVector3 b01 = boundary[(i + 1) % bcount] - boundary[i]; IfcVector3 b12 = boundary[(i + 2) % bcount] - boundary[(i + 1) % bcount]; - IfcVector3 b1_side = IfcVector3(b01.y, -b01.x, 0.0); // rotated 90 clockwise in Z plane + IfcVector3 b1_side = IfcVector3(b01.y, -b01.x, 0.0); // rotated 90° clockwise in Z plane // Warning: rough estimate only. A concave poly with lots of small segments each featuring a small counter rotation // could fool the accumulation. Correct implementation would be sum( acos( b01 * b2) * sign( b12 * b1_side)) windingOrder += (b1_side.x*b12.x + b1_side.y*b12.y); diff --git a/third_party/libassimp/code/Importer/IFC/IFCCurve.cpp b/third_party/libassimp/code/Importer/IFC/IFCCurve.cpp index af58e7b105..a817b4f9f5 100644 --- a/third_party/libassimp/code/Importer/IFC/IFCCurve.cpp +++ b/third_party/libassimp/code/Importer/IFC/IFCCurve.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -311,10 +311,9 @@ class TrimmedCurve : public BoundedCurve { public: // -------------------------------------------------- TrimmedCurve(const Schema_2x3::IfcTrimmedCurve& entity, ConversionData& conv) - : BoundedCurve(entity,conv) + : BoundedCurve(entity,conv), + base(std::shared_ptr(Curve::Convert(entity.BasisCurve,conv))) { - base = std::shared_ptr(Curve::Convert(entity.BasisCurve,conv)); - typedef std::shared_ptr Entry; // for some reason, trimmed curves can either specify a parametric value @@ -500,7 +499,7 @@ bool Curve::InRange(IfcFloat u) const { if (IsClosed()) { return true; } - const IfcFloat epsilon = 1e-5; + const IfcFloat epsilon = Math::getEpsilon(); return u - range.first > -epsilon && range.second - u > -epsilon; } #endif diff --git a/third_party/libassimp/code/Importer/IFC/IFCGeometry.cpp b/third_party/libassimp/code/Importer/IFC/IFCGeometry.cpp index 548de4e27e..d1c7aee19c 100644 --- a/third_party/libassimp/code/Importer/IFC/IFCGeometry.cpp +++ b/third_party/libassimp/code/Importer/IFC/IFCGeometry.cpp @@ -46,17 +46,22 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_IFC_IMPORTER #include "IFCUtil.h" -#include "code/PolyTools.h" -#include "code/ProcessHelper.h" +#include "Common/PolyTools.h" +#include "PostProcessing/ProcessHelper.h" + +#ifdef ASSIMP_USE_HUNTER +# include +# include +#else +# include "../contrib/poly2tri/poly2tri/poly2tri.h" +# include "../contrib/clipper/clipper.hpp" +#endif -#include "../contrib/poly2tri/poly2tri/poly2tri.h" -#include "../contrib/clipper/clipper.hpp" #include - #include namespace Assimp { - namespace IFC { +namespace IFC { // ------------------------------------------------------------------------------------------------ bool ProcessPolyloop(const Schema_2x3::IfcPolyLoop& loop, TempMesh& meshout, ConversionData& /*conv*/) @@ -123,7 +128,7 @@ void ProcessPolygonBoundaries(TempMesh& result, const TempMesh& inmesh, size_t m outer_polygon_it = begin + master_bounds; } else { - for(iit = begin; iit != end; iit++) { + for(iit = begin; iit != end; ++iit) { // find the polygon with the largest area and take it as the outer bound. IfcVector3& n = normals[std::distance(begin,iit)]; const IfcFloat area = n.SquareLength(); diff --git a/third_party/libassimp/code/Importer/IFC/IFCLoader.cpp b/third_party/libassimp/code/Importer/IFC/IFCLoader.cpp index 4733555381..5c705c2566 100644 --- a/third_party/libassimp/code/Importer/IFC/IFCLoader.cpp +++ b/third_party/libassimp/code/Importer/IFC/IFCLoader.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -52,7 +52,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #ifndef ASSIMP_BUILD_NO_COMPRESSED_IFC -# include +# ifdef ASSIMP_USE_HUNTER +# include +# else +# include +# endif #endif #include "IFCLoader.h" @@ -207,10 +211,21 @@ void IFCImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOS } uint8_t* buff = new uint8_t[fileInfo.uncompressed_size]; LogInfo("Decompressing IFCZIP file"); - unzOpenCurrentFile( zip ); - const int ret = unzReadCurrentFile( zip, buff, fileInfo.uncompressed_size); + unzOpenCurrentFile(zip); + size_t total = 0; + int read = 0; + do { + int bufferSize = fileInfo.uncompressed_size < INT16_MAX ? fileInfo.uncompressed_size : INT16_MAX; + void* buffer = malloc(bufferSize); + read = unzReadCurrentFile(zip, buffer, bufferSize); + if (read > 0) { + memcpy((char*)buff + total, buffer, read); + total += read; + } + free(buffer); + } while (read > 0); size_t filesize = fileInfo.uncompressed_size; - if ( ret < 0 || size_t(ret) != filesize ) + if (total == 0 || size_t(total) != filesize) { delete[] buff; ThrowException("Failed to decompress IFC ZIP file"); @@ -659,8 +674,8 @@ void ProcessMetadata(uint64_t relDefinesByPropertiesID, ConversionData& conv, Me } // ------------------------------------------------------------------------------------------------ -aiNode* ProcessSpatialStructure(aiNode* parent, const Schema_2x3::IfcProduct& el, ConversionData& conv, std::vector* collect_openings = NULL) -{ +aiNode* ProcessSpatialStructure(aiNode* parent, const Schema_2x3::IfcProduct& el, ConversionData& conv, + std::vector* collect_openings = nullptr ) { const STEP::DB::RefMap& refs = conv.db.GetRefs(); // skip over space and annotation nodes - usually, these have no meaning in Assimp's context @@ -675,12 +690,12 @@ aiNode* ProcessSpatialStructure(aiNode* parent, const Schema_2x3::IfcProduct& el if(conv.settings.skipAnnotations) { if(el.ToPtr()) { IFCImporter::LogDebug("skipping IfcAnnotation entity due to importer settings"); - return NULL; + return nullptr; } } // add an output node for this spatial structure - std::unique_ptr nd(new aiNode()); + aiNode *nd(new aiNode ); nd->mName.Set(el.GetClassName()+"_"+(el.Name?el.Name.Get():"Unnamed")+"_"+el.GlobalId); nd->mParent = parent; @@ -693,8 +708,7 @@ aiNode* ProcessSpatialStructure(aiNode* parent, const Schema_2x3::IfcProduct& el if (children.first==children.second) { // handles single property set ProcessMetadata((*children.first).second, conv, properties); - } - else { + } else { // handles multiple property sets (currently all property sets are merged, // which may not be the best solution in the long run) for (STEP::DB::RefMap::const_iterator it=children.first; it!=children.second; ++it) { @@ -751,7 +765,7 @@ aiNode* ProcessSpatialStructure(aiNode* parent, const Schema_2x3::IfcProduct& el continue; } - aiNode* const ndnew = ProcessSpatialStructure(nd.get(),pro,conv,NULL); + aiNode* const ndnew = ProcessSpatialStructure(nd,pro,conv,nullptr); if(ndnew) { subnodes.push_back( ndnew ); } @@ -765,7 +779,7 @@ aiNode* ProcessSpatialStructure(aiNode* parent, const Schema_2x3::IfcProduct& el // move opening elements to a separate node since they are semantically different than elements that are just 'contained' std::unique_ptr nd_aggr(new aiNode()); nd_aggr->mName.Set("$RelVoidsElement"); - nd_aggr->mParent = nd.get(); + nd_aggr->mParent = nd; nd_aggr->mTransformation = nd->mTransformation; @@ -810,7 +824,7 @@ aiNode* ProcessSpatialStructure(aiNode* parent, const Schema_2x3::IfcProduct& el // move aggregate elements to a separate node since they are semantically different than elements that are just 'contained' std::unique_ptr nd_aggr(new aiNode()); nd_aggr->mName.Set("$RelAggregates"); - nd_aggr->mParent = nd.get(); + nd_aggr->mParent = nd; nd_aggr->mTransformation = nd->mTransformation; @@ -835,19 +849,18 @@ aiNode* ProcessSpatialStructure(aiNode* parent, const Schema_2x3::IfcProduct& el } if (!skipGeometry) { - ProcessProductRepresentation(el,nd.get(),subnodes,conv); - conv.apply_openings = conv.collect_openings = NULL; + ProcessProductRepresentation(el, nd, subnodes, conv); + conv.apply_openings = conv.collect_openings = nullptr; } if (subnodes.size()) { nd->mChildren = new aiNode*[subnodes.size()](); for(aiNode* nd2 : subnodes) { nd->mChildren[nd->mNumChildren++] = nd2; - nd2->mParent = nd.get(); + nd2->mParent = nd; } } - } - catch(...) { + } catch(...) { // it hurts, but I don't want to pull boost::ptr_vector into -noboost only for these few spots here std::for_each(subnodes.begin(),subnodes.end(),delete_fun()); throw; @@ -855,7 +868,7 @@ aiNode* ProcessSpatialStructure(aiNode* parent, const Schema_2x3::IfcProduct& el ai_assert(conv.already_processed.find(el.GetID()) != conv.already_processed.end()); conv.already_processed.erase(conv.already_processed.find(el.GetID())); - return nd.release(); + return nd; } // ------------------------------------------------------------------------------------------------ diff --git a/third_party/libassimp/code/Importer/IFC/IFCLoader.h b/third_party/libassimp/code/Importer/IFC/IFCLoader.h index 99e3e8ed9a..678c60343d 100644 --- a/third_party/libassimp/code/Importer/IFC/IFCLoader.h +++ b/third_party/libassimp/code/Importer/IFC/IFCLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/Importer/IFC/IFCMaterial.cpp b/third_party/libassimp/code/Importer/IFC/IFCMaterial.cpp index 423d1471ea..5fda0a1de0 100644 --- a/third_party/libassimp/code/Importer/IFC/IFCMaterial.cpp +++ b/third_party/libassimp/code/Importer/IFC/IFCMaterial.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/Importer/IFC/IFCOpenings.cpp b/third_party/libassimp/code/Importer/IFC/IFCOpenings.cpp index c5720e9431..d6c40b3839 100644 --- a/third_party/libassimp/code/Importer/IFC/IFCOpenings.cpp +++ b/third_party/libassimp/code/Importer/IFC/IFCOpenings.cpp @@ -46,11 +46,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_IFC_IMPORTER #include "IFCUtil.h" -#include "code/PolyTools.h" -#include "code/ProcessHelper.h" +#include "Common/PolyTools.h" +#include "PostProcessing/ProcessHelper.h" -#include "../contrib/poly2tri/poly2tri/poly2tri.h" -#include "../contrib/clipper/clipper.hpp" +#ifdef ASSIMP_USE_HUNTER +# include +# include +#else +# include "../contrib/poly2tri/poly2tri/poly2tri.h" +# include "../contrib/clipper/clipper.hpp" +#endif #include @@ -588,7 +593,7 @@ typedef std::vector(); return (std::fabs(bb.second.x - ibb.first.x) < epsilon && bb.first.y <= ibb.second.y && bb.second.y >= ibb.first.y) || (std::fabs(bb.first.x - ibb.second.x) < epsilon && ibb.first.y <= bb.second.y && ibb.second.y >= bb.first.y) || (std::fabs(bb.second.y - ibb.first.y) < epsilon && bb.first.x <= ibb.second.x && bb.second.x >= ibb.first.x) || @@ -676,7 +681,7 @@ bool IntersectingLineSegments(const IfcVector2& n0, const IfcVector2& n1, // ------------------------------------------------------------------------------------------------ void FindAdjacentContours(ContourVector::iterator current, const ContourVector& contours) { - const IfcFloat sqlen_epsilon = static_cast(1e-8); + const IfcFloat sqlen_epsilon = static_cast(Math::getEpsilon()); const BoundingBox& bb = (*current).bb; // What is to be done here is to populate the skip lists for the contour @@ -753,7 +758,7 @@ void FindAdjacentContours(ContourVector::iterator current, const ContourVector& // ------------------------------------------------------------------------------------------------ AI_FORCE_INLINE bool LikelyBorder(const IfcVector2& vdelta) { - const IfcFloat dot_point_epsilon = static_cast(1e-5); + const IfcFloat dot_point_epsilon = static_cast(Math::getEpsilon()); return std::fabs(vdelta.x * vdelta.y) < dot_point_epsilon; } diff --git a/third_party/libassimp/code/Importer/IFC/IFCProfile.cpp b/third_party/libassimp/code/Importer/IFC/IFCProfile.cpp index 2236d0d9b9..daafc9afed 100644 --- a/third_party/libassimp/code/Importer/IFC/IFCProfile.cpp +++ b/third_party/libassimp/code/Importer/IFC/IFCProfile.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/Importer/IFC/IFCReaderGen_2x3.h b/third_party/libassimp/code/Importer/IFC/IFCReaderGen_2x3.h index 0362d90b27..8b39ccdc22 100644 --- a/third_party/libassimp/code/Importer/IFC/IFCReaderGen_2x3.h +++ b/third_party/libassimp/code/Importer/IFC/IFCReaderGen_2x3.h @@ -43,7 +43,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef INCLUDED_IFC_READER_GEN_H #define INCLUDED_IFC_READER_GEN_H -#include "code/STEPFile.h" +#include "code/Step/STEPFile.h" namespace Assimp { namespace IFC { diff --git a/third_party/libassimp/code/Importer/IFC/IFCUtil.cpp b/third_party/libassimp/code/Importer/IFC/IFCUtil.cpp index 06cc4405ab..f6bca91f56 100644 --- a/third_party/libassimp/code/Importer/IFC/IFCUtil.cpp +++ b/third_party/libassimp/code/Importer/IFC/IFCUtil.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -44,21 +44,18 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * @brief Implementation of conversion routines for some common Ifc helper entities. */ - - #ifndef ASSIMP_BUILD_NO_IFC_IMPORTER -#include "code/Importer/IFC/IFCUtil.h" -#include "code/PolyTools.h" -#include "code/ProcessHelper.h" +#include "Importer/IFC/IFCUtil.h" +#include "Common/PolyTools.h" +#include "PostProcessing/ProcessHelper.h" #include namespace Assimp { - namespace IFC { +namespace IFC { // ------------------------------------------------------------------------------------------------ -void TempOpening::Transform(const IfcMatrix4& mat) -{ +void TempOpening::Transform(const IfcMatrix4& mat) { if(profileMesh) { profileMesh->Transform(mat); } diff --git a/third_party/libassimp/code/Importer/IFC/IFCUtil.h b/third_party/libassimp/code/Importer/IFC/IFCUtil.h index 194206d4bf..32ae1e07f7 100644 --- a/third_party/libassimp/code/Importer/IFC/IFCUtil.h +++ b/third_party/libassimp/code/Importer/IFC/IFCUtil.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -49,7 +49,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "IFCReaderGen_2x3.h" #include "IFCLoader.h" -#include "code/STEPFile.h" +#include "code/Step/STEPFile.h" #include #include diff --git a/third_party/libassimp/code/Importer/STEPParser/STEPFileEncoding.cpp b/third_party/libassimp/code/Importer/STEPParser/STEPFileEncoding.cpp index 70d5f4e4b7..101dcdfd73 100644 --- a/third_party/libassimp/code/Importer/STEPParser/STEPFileEncoding.cpp +++ b/third_party/libassimp/code/Importer/STEPParser/STEPFileEncoding.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -45,7 +45,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "STEPFileEncoding.h" #include -#include +#ifdef ASSIMP_USE_HUNTER +# include +#else +# include +#endif #include diff --git a/third_party/libassimp/code/Importer/STEPParser/STEPFileEncoding.h b/third_party/libassimp/code/Importer/STEPParser/STEPFileEncoding.h index 232cb81ba7..09f16ba337 100644 --- a/third_party/libassimp/code/Importer/STEPParser/STEPFileEncoding.h +++ b/third_party/libassimp/code/Importer/STEPParser/STEPFileEncoding.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/Importer/STEPParser/STEPFileReader.cpp b/third_party/libassimp/code/Importer/STEPParser/STEPFileReader.cpp index c7cad05ae3..f099d2be73 100644 --- a/third_party/libassimp/code/Importer/STEPParser/STEPFileReader.cpp +++ b/third_party/libassimp/code/Importer/STEPParser/STEPFileReader.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -63,7 +63,6 @@ std::string AddLineNumber(const std::string& s,uint64_t line /*= LINE_NOT_SPECIF return line == STEP::SyntaxError::LINE_NOT_SPECIFIED ? prefix+s : static_cast( (Formatter::format(),prefix,"(line ",line,") ",s) ); } - // ------------------------------------------------------------------------------------------------ std::string AddEntityID(const std::string& s,uint64_t entity /*= ENTITY_NOT_SPECIFIED*/, const std::string& prefix = "") { @@ -243,7 +242,6 @@ void STEP::ReadFile(DB& db,const EXPRESS::ConversionSchema& scheme, std::string::size_type n2 = s.find_last_of(')'); if (n2 == std::string::npos || n2 < n1 || n2 == s.length() - 1 || s[n2 + 1] != ';') { - has_next = true; bool ok = false; for( ++splitter; splitter; ++splitter) { @@ -251,14 +249,14 @@ void STEP::ReadFile(DB& db,const EXPRESS::ConversionSchema& scheme, if (snext.empty()) { continue; } + // the next line doesn't start an entity, so maybe it is // just a continuation for this line, keep going if (!IsEntityDef(snext)) { s.append(snext); n2 = s.find_last_of(')'); ok = !(n2 == std::string::npos || n2 < n1 || n2 == s.length() - 1 || s[n2 + 1] != ';'); - } - else { + } else { break; } } @@ -280,10 +278,10 @@ void STEP::ReadFile(DB& db,const EXPRESS::ConversionSchema& scheme, std::transform( type.begin(), type.end(), type.begin(), &Assimp::ToLower ); const char* sz = scheme.GetStaticStringForToken(type); if(sz) { - const std::string::size_type len = n2-n1+1; - char* const copysz = new char[len+1]; + const std::string::size_type szLen = n2-n1+1; + char* const copysz = new char[szLen+1]; std::copy(s.c_str()+n1,s.c_str()+n2+1,copysz); - copysz[len] = '\0'; + copysz[szLen] = '\0'; db.InternInsert(new LazyObject(db,id,line,sz,copysz)); } if(!has_next) { @@ -424,10 +422,8 @@ std::shared_ptr EXPRESS::DataType::Parse(const char*& i return std::make_shared(neg?-num:num); } - // ------------------------------------------------------------------------------------------------ -std::shared_ptr EXPRESS::LIST::Parse(const char*& inout,uint64_t line, const EXPRESS::ConversionSchema* schema /*= NULL*/) -{ +std::shared_ptr EXPRESS::LIST::Parse(const char*& inout,uint64_t line, const EXPRESS::ConversionSchema* schema /*= NULL*/) { const std::shared_ptr list = std::make_shared(); EXPRESS::LIST::MemberList& members = list->members; @@ -468,61 +464,73 @@ std::shared_ptr EXPRESS::LIST::Parse(const char*& inout,uin return list; } +// ------------------------------------------------------------------------------------------------ +static void handleSkippedDepthFromToken(const char *a, int64_t &skip_depth ) { + if (*a == '(') { + ++skip_depth; + } else if (*a == ')') { + --skip_depth; + } +} + +// ------------------------------------------------------------------------------------------------ +static int64_t getIdFromToken(const char *a) { + const char *tmp; + const int64_t num = static_cast(strtoul10_64(a + 1, &tmp)); + + return num; +} // ------------------------------------------------------------------------------------------------ STEP::LazyObject::LazyObject(DB& db, uint64_t id,uint64_t /*line*/, const char* const type,const char* args) - : id(id) - , type(type) - , db(db) - , args(args) - , obj() -{ +: id(id) +, type(type) +, db(db) +, args(args) +, obj() { // find any external references and store them in the database. // this helps us emulate STEPs INVERSE fields. - if (db.KeepInverseIndicesForType(type)) { - const char* a = args; + if (!db.KeepInverseIndicesForType(type)) { + return; + } - // do a quick scan through the argument tuple and watch out for entity references - int64_t skip_depth = 0; - while(*a) { - if (*a == '(') { - ++skip_depth; - } - else if (*a == ')') { - --skip_depth; - } + // do a quick scan through the argument tuple and watch out for entity references + const char *a( args ); + int64_t skip_depth( 0 ); + while ( *a ) { + handleSkippedDepthFromToken(a, skip_depth); + /*if (*a == '(') { + ++skip_depth; + } else if (*a == ')') { + --skip_depth; + }*/ - if (skip_depth >= 1 && *a=='#') { - if (*(a + 1) != '#') - { - const char* tmp; - const int64_t num = static_cast(strtoul10_64(a + 1, &tmp)); - db.MarkRef(num, id); - } - else - { - ++a; - } - } - ++a; + if (skip_depth >= 1 && *a=='#') { + if (*(a + 1) != '#') { + /*const char *tmp; + const int64_t num = static_cast(strtoul10_64(a + 1, &tmp)); + db.MarkRef(num, id);*/ + db.MarkRef(getIdFromToken(a), id); + } else { + ++a; + } } - + ++a; } } // ------------------------------------------------------------------------------------------------ -STEP::LazyObject::~LazyObject() -{ +STEP::LazyObject::~LazyObject() { // make sure the right dtor/operator delete get called if (obj) { delete obj; + } else { + delete[] args; } - else delete[] args; } // ------------------------------------------------------------------------------------------------ -void STEP::LazyObject::LazyInit() const -{ +void STEP::LazyObject::LazyInit() const { const EXPRESS::ConversionSchema& schema = db.GetSchema(); STEP::ConvertObjectProc proc = schema.GetConverterProc(type); diff --git a/third_party/libassimp/code/Importer/STEPParser/STEPFileReader.h b/third_party/libassimp/code/Importer/STEPParser/STEPFileReader.h index 667d28bfd0..9c4b772411 100644 --- a/third_party/libassimp/code/Importer/STEPParser/STEPFileReader.h +++ b/third_party/libassimp/code/Importer/STEPParser/STEPFileReader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -43,7 +43,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef INCLUDED_AI_STEPFILEREADER_H #define INCLUDED_AI_STEPFILEREADER_H -#include "code/STEPFile.h" +#include "code/Step/STEPFile.h" namespace Assimp { namespace STEP { @@ -68,4 +68,4 @@ void ReadFile(DB& db,const EXPRESS::ConversionSchema& scheme, const char* const } // ! STEP } // ! Assimp -#endif +#endif // INCLUDED_AI_STEPFILEREADER_H diff --git a/third_party/libassimp/code/Importer/StepFile/StepFileGen1.cpp b/third_party/libassimp/code/Importer/StepFile/StepFileGen1.cpp index 32df66c17d..50c54818e4 100644 --- a/third_party/libassimp/code/Importer/StepFile/StepFileGen1.cpp +++ b/third_party/libassimp/code/Importer/StepFile/StepFileGen1.cpp @@ -40,7 +40,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** MACHINE-GENERATED by scripts/ICFImporter/CppGenerator.py */ -#ifndef ASSIMP_BUILD_NO_STEPFILE_IMPORTER +#ifndef ASSIMP_BUILD_NO_STEP_IMPORTER #include "code/Importer/StepFile/StepReaderGen.h" diff --git a/third_party/libassimp/code/Importer/StepFile/StepFileImporter.cpp b/third_party/libassimp/code/Importer/StepFile/StepFileImporter.cpp index 9bfaf7051e..26c456ac98 100644 --- a/third_party/libassimp/code/Importer/StepFile/StepFileImporter.cpp +++ b/third_party/libassimp/code/Importer/StepFile/StepFileImporter.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -41,7 +41,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ -#ifndef ASSIMP_BUILD_NO_STEPFILE_IMPORTER +#ifndef ASSIMP_BUILD_NO_STEP_IMPORTER #include "StepFileImporter.h" #include "../../Importer/STEPParser/STEPFileReader.h" @@ -110,5 +110,5 @@ void StepFileImporter::InternReadFile(const std::string &file, aiScene* pScene, } // Namespace StepFile } // Namespace Assimp -#endif // ASSIMP_BUILD_NO_STEPFILE_IMPORTER +#endif // ASSIMP_BUILD_NO_STEP_IMPORTER diff --git a/third_party/libassimp/code/Importer/StepFile/StepFileImporter.h b/third_party/libassimp/code/Importer/StepFile/StepFileImporter.h index 7314a54f30..70f65fdcfd 100644 --- a/third_party/libassimp/code/Importer/StepFile/StepFileImporter.h +++ b/third_party/libassimp/code/Importer/StepFile/StepFileImporter.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -43,7 +43,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma once -#ifndef ASSIMP_BUILD_NO_STEPFILE_IMPORTER +#ifndef ASSIMP_BUILD_NO_STEP_IMPORTER #include @@ -66,4 +66,4 @@ private: } // Namespace StepFile } // Namespace Assimp -#endif // ASSIMP_BUILD_NO_STEPFILE_IMPORTER +#endif // ASSIMP_BUILD_NO_STEP_IMPORTER diff --git a/third_party/libassimp/code/Importer/StepFile/StepReaderGen.h b/third_party/libassimp/code/Importer/StepFile/StepReaderGen.h index 21f2518dfb..9eb86c3328 100644 --- a/third_party/libassimp/code/Importer/StepFile/StepReaderGen.h +++ b/third_party/libassimp/code/Importer/StepFile/StepReaderGen.h @@ -43,7 +43,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef INCLUDED_STEPFILE_READER_GEN_H #define INCLUDED_STEPFILE_READER_GEN_H -#include "code/STEPFile.h" +#include "code/Step/STEPFile.h" namespace Assimp { namespace StepFile { diff --git a/third_party/libassimp/code/IRRLoader.cpp b/third_party/libassimp/code/Irr/IRRLoader.cpp similarity index 97% rename from third_party/libassimp/code/IRRLoader.cpp rename to third_party/libassimp/code/Irr/IRRLoader.cpp index 0640b0d660..e94fd85a4d 100644 --- a/third_party/libassimp/code/IRRLoader.cpp +++ b/third_party/libassimp/code/Irr/IRRLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -49,18 +49,15 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_IRR_IMPORTER -#include "IRRLoader.h" +#include "Irr/IRRLoader.h" +#include "Common/Importer.h" + #include #include #include - #include #include -#include "Importer.h" - -// We need MathFunctions.h to compute the lcm/gcd of a number #include -#include #include #include #include @@ -69,6 +66,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include +#include + using namespace Assimp; using namespace irr; using namespace irr::io; @@ -89,14 +88,16 @@ static const aiImporterDesc desc = { // ------------------------------------------------------------------------------------------------ // Constructor to be privately used by Importer IRRImporter::IRRImporter() - : fps(), - configSpeedFlag() -{} +: fps() +, configSpeedFlag(){ + // empty +} // ------------------------------------------------------------------------------------------------ // Destructor, private as well -IRRImporter::~IRRImporter() -{} +IRRImporter::~IRRImporter() { + // empty +} // ------------------------------------------------------------------------------------------------ // Returns whether the class can handle the format of the given file. @@ -107,9 +108,9 @@ bool IRRImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool } else if (extension == "xml" || checkSig) { /* If CanRead() is called in order to check whether we * support a specific file extension in general pIOHandler - * might be NULL and it's our duty to return true here. + * might be nullptr and it's our duty to return true here. */ - if ( nullptr == pIOHandler ) { + if (nullptr == pIOHandler ) { return true; } const char* tokens[] = {"irr_scene"}; @@ -290,31 +291,30 @@ void IRRImporter::CopyMaterial(std::vector& materials, // ------------------------------------------------------------------------------------------------ -inline int ClampSpline(int idx, int size) -{ +inline +int ClampSpline(int idx, int size) { return ( idx<0 ? size+idx : ( idx>=size ? idx-size : idx ) ); } // ------------------------------------------------------------------------------------------------ inline void FindSuitableMultiple(int& angle) { - if (angle < 3)angle = 3; + if (angle < 3) angle = 3; else if (angle < 10) angle = 10; else if (angle < 20) angle = 20; else if (angle < 30) angle = 30; - else - { - } } // ------------------------------------------------------------------------------------------------ void IRRImporter::ComputeAnimations(Node* root, aiNode* real, std::vector& anims) { - ai_assert(NULL != root && NULL != real); + ai_assert(nullptr != root && nullptr != real); // XXX totally WIP - doesn't produce proper results, need to evaluate // whether there's any use for Irrlicht's proprietary scene format // outside Irrlicht ... + // This also applies to the above function of FindSuitableMultiple and ClampSpline which are + // solely used in this function if (root->animators.empty()) { return; @@ -521,7 +521,8 @@ void IRRImporter::ComputeAnimations(Node* root, aiNode* real, std::vectorid); - if (!scene) { + aiScene* localScene = batch.GetImport(root->id); + if (!localScene) { ASSIMP_LOG_ERROR("IRR: Unable to load external file: " + root->meshPath); break; } - attach.push_back(AttachmentInfo(scene,rootOut)); + attach.push_back(AttachmentInfo(localScene,rootOut)); // Now combine the material we've loaded for this mesh // with the real materials we got from the file. As we // don't execute any pp-steps on the file, the numbers // should be equal. If they are not, we can impossibly // do this ... - if (root->materials.size() != (unsigned int)scene->mNumMaterials) { + if (root->materials.size() != (unsigned int)localScene->mNumMaterials) { ASSIMP_LOG_WARN("IRR: Failed to match imported materials " "with the materials found in the IRR scene file"); break; } - for (unsigned int i = 0; i < scene->mNumMaterials;++i) { + for (unsigned int i = 0; i < localScene->mNumMaterials;++i) { // Delete the old material, we don't need it anymore - delete scene->mMaterials[i]; + delete localScene->mMaterials[i]; std::pair& src = root->materials[i]; - scene->mMaterials[i] = src.first; + localScene->mMaterials[i] = src.first; } // NOTE: Each mesh should have exactly one material assigned, // but we do it in a separate loop if this behaviour changes // in future. - for (unsigned int i = 0; i < scene->mNumMeshes;++i) { + for (unsigned int i = 0; i < localScene->mNumMeshes;++i) { // Process material flags - aiMesh* mesh = scene->mMeshes[i]; + aiMesh* mesh = localScene->mMeshes[i]; // If "trans_vertex_alpha" mode is enabled, search all vertex colors @@ -905,8 +906,9 @@ void IRRImporter::InternReadFile( const std::string& pFile, std::unique_ptr file( pIOHandler->Open( pFile)); // Check whether we can read from the file - if( file.get() == NULL) - throw DeadlyImportError( "Failed to open IRR file " + pFile + ""); + if (file.get() == nullptr) { + throw DeadlyImportError("Failed to open IRR file " + pFile + ""); + } // Construct the irrXML parser CIrrXML_IOStreamReader st(file.get()); @@ -914,14 +916,14 @@ void IRRImporter::InternReadFile( const std::string& pFile, // The root node of the scene Node* root = new Node(Node::DUMMY); - root->parent = NULL; + root->parent = nullptr; root->name = ""; // Current node parent Node* curParent = root; // Scenegraph node we're currently working on - Node* curNode = NULL; + Node* curNode = nullptr; // List of output cameras std::vector cameras; @@ -1048,7 +1050,7 @@ void IRRImporter::InternReadFile( const std::string& pFile, continue; } - Animator* curAnim = NULL; + Animator* curAnim = nullptr; // Materials can occur for nearly any type of node if (inMaterials && curNode->type != Node::DUMMY) { @@ -1353,7 +1355,7 @@ void IRRImporter::InternReadFile( const std::string& pFile, } else curParent = curParent->parent; } - else curNode = NULL; + else curNode = nullptr; } // clear all flags else if (!ASSIMP_stricmp(reader->getNodeName(),"materials")) { @@ -1479,7 +1481,8 @@ void IRRImporter::InternReadFile( const std::string& pFile, /* Finished ... everything destructs automatically and all * temporary scenes have already been deleted by MergeScenes() */ - return; + + delete root; } #endif // !! ASSIMP_BUILD_NO_IRR_IMPORTER diff --git a/third_party/libassimp/code/IRRLoader.h b/third_party/libassimp/code/Irr/IRRLoader.h similarity index 94% rename from third_party/libassimp/code/IRRLoader.h rename to third_party/libassimp/code/Irr/IRRLoader.h index 3bd39092ad..b3ad81a7d7 100644 --- a/third_party/libassimp/code/IRRLoader.h +++ b/third_party/libassimp/code/Irr/IRRLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -48,15 +48,15 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_IRRLOADER_H_INCLUDED #define AI_IRRLOADER_H_INCLUDED -#include "IRRShared.h" +#include "Irr/IRRShared.h" +#include "Common/Importer.h" + #include -#include "Importer.h" #include #include namespace Assimp { - // --------------------------------------------------------------------------- /** Irr importer class. * @@ -64,15 +64,11 @@ namespace Assimp { * irrEdit. As IrrEdit itself is capable of importing quite many file formats, * it might be a good file format for data exchange. */ -class IRRImporter : public BaseImporter, public IrrlichtBase -{ +class IRRImporter : public BaseImporter, public IrrlichtBase { public: IRRImporter(); ~IRRImporter(); - -public: - // ------------------------------------------------------------------- /** Returns whether the class can handle the format of the given file. * See BaseImporter::CanRead() for details. @@ -81,32 +77,17 @@ public: bool checkSig) const; protected: - - // ------------------------------------------------------------------- - /** - */ const aiImporterDesc* GetInfo () const; - - // ------------------------------------------------------------------- - /** - */ - void InternReadFile( const std::string& pFile, aiScene* pScene, - IOSystem* pIOHandler); - - // ------------------------------------------------------------------- - /** - */ + void InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler); void SetupProperties(const Importer* pImp); private: /** Data structure for a scenegraph node animator */ - struct Animator - { + struct Animator { // Type of the animator - enum AT - { + enum AT { UNKNOWN = 0x0, ROTATION = 0x1, FLY_CIRCLE = 0x2, diff --git a/third_party/libassimp/code/IRRMeshLoader.cpp b/third_party/libassimp/code/Irr/IRRMeshLoader.cpp similarity index 99% rename from third_party/libassimp/code/IRRMeshLoader.cpp rename to third_party/libassimp/code/Irr/IRRMeshLoader.cpp index 85de421957..f3aed59434 100644 --- a/third_party/libassimp/code/IRRMeshLoader.cpp +++ b/third_party/libassimp/code/Irr/IRRMeshLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/IRRMeshLoader.h b/third_party/libassimp/code/Irr/IRRMeshLoader.h similarity index 98% rename from third_party/libassimp/code/IRRMeshLoader.h rename to third_party/libassimp/code/Irr/IRRMeshLoader.h index ef6a8a11ba..d8b42d78da 100644 --- a/third_party/libassimp/code/IRRMeshLoader.h +++ b/third_party/libassimp/code/Irr/IRRMeshLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/IRRShared.cpp b/third_party/libassimp/code/Irr/IRRShared.cpp similarity index 99% rename from third_party/libassimp/code/IRRShared.cpp rename to third_party/libassimp/code/Irr/IRRShared.cpp index 1e69f1d090..ecac031ab1 100644 --- a/third_party/libassimp/code/IRRShared.cpp +++ b/third_party/libassimp/code/Irr/IRRShared.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/IRRShared.h b/third_party/libassimp/code/Irr/IRRShared.h similarity index 100% rename from third_party/libassimp/code/IRRShared.h rename to third_party/libassimp/code/Irr/IRRShared.h diff --git a/third_party/libassimp/code/LWOAnimation.cpp b/third_party/libassimp/code/LWO/LWOAnimation.cpp similarity index 99% rename from third_party/libassimp/code/LWOAnimation.cpp rename to third_party/libassimp/code/LWO/LWOAnimation.cpp index ff02a8eab8..3a0d2c3922 100644 --- a/third_party/libassimp/code/LWOAnimation.cpp +++ b/third_party/libassimp/code/LWO/LWOAnimation.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/LWOAnimation.h b/third_party/libassimp/code/LWO/LWOAnimation.h similarity index 99% rename from third_party/libassimp/code/LWOAnimation.h rename to third_party/libassimp/code/LWO/LWOAnimation.h index f7b0f177bc..dd29695cc4 100644 --- a/third_party/libassimp/code/LWOAnimation.h +++ b/third_party/libassimp/code/LWO/LWOAnimation.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/LWOBLoader.cpp b/third_party/libassimp/code/LWO/LWOBLoader.cpp similarity index 99% rename from third_party/libassimp/code/LWOBLoader.cpp rename to third_party/libassimp/code/LWO/LWOBLoader.cpp index fabf99cad3..b24957072e 100644 --- a/third_party/libassimp/code/LWOBLoader.cpp +++ b/third_party/libassimp/code/LWO/LWOBLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/LWOFileData.h b/third_party/libassimp/code/LWO/LWOFileData.h similarity index 99% rename from third_party/libassimp/code/LWOFileData.h rename to third_party/libassimp/code/LWO/LWOFileData.h index b3a9631999..7d1f6b1df0 100644 --- a/third_party/libassimp/code/LWOFileData.h +++ b/third_party/libassimp/code/LWO/LWOFileData.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -57,8 +57,8 @@ The chunks are taken from the official LightWave SDK headers. #include // internal headers -#include "IFF.h" -#include "LWOAnimation.h" +#include "Common/IFF.h" +#include "LWO/LWOAnimation.h" namespace Assimp { namespace LWO { diff --git a/third_party/libassimp/code/LWOLoader.cpp b/third_party/libassimp/code/LWO/LWOLoader.cpp similarity index 99% rename from third_party/libassimp/code/LWOLoader.cpp rename to third_party/libassimp/code/LWO/LWOLoader.cpp index fbefe4a1e0..1e5b92c327 100644 --- a/third_party/libassimp/code/LWOLoader.cpp +++ b/third_party/libassimp/code/LWO/LWOLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -49,14 +49,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_LWO_IMPORTER // internal headers -#include "LWOLoader.h" +#include "LWO/LWOLoader.h" +#include "PostProcessing/ProcessHelper.h" +#include "PostProcessing/ConvertToLHProcess.h" + #include #include #include -#include "ProcessHelper.h" -#include "ConvertToLHProcess.h" #include #include + #include #include #include @@ -1326,6 +1328,7 @@ void LWOImporter::LoadLWO2File() bool skip = false; LE_NCONST uint8_t* const end = mFileBuffer + fileSize; + unsigned int iUnnamed = 0; while (true) { if (mFileBuffer + sizeof(IFF::ChunkHeader) > end)break; @@ -1337,7 +1340,6 @@ void LWOImporter::LoadLWO2File() break; } uint8_t* const next = mFileBuffer+head.length; - unsigned int iUnnamed = 0; if(!head.length) { mFileBuffer = next; diff --git a/third_party/libassimp/code/LWOLoader.h b/third_party/libassimp/code/LWO/LWOLoader.h similarity index 99% rename from third_party/libassimp/code/LWOLoader.h rename to third_party/libassimp/code/LWO/LWOLoader.h index 4d42eb2d2d..05b958fd2a 100644 --- a/third_party/libassimp/code/LWOLoader.h +++ b/third_party/libassimp/code/LWO/LWOLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/LWOMaterial.cpp b/third_party/libassimp/code/LWO/LWOMaterial.cpp similarity index 99% rename from third_party/libassimp/code/LWOMaterial.cpp rename to third_party/libassimp/code/LWO/LWOMaterial.cpp index 15c2104606..b54c21c26b 100644 --- a/third_party/libassimp/code/LWOMaterial.cpp +++ b/third_party/libassimp/code/LWO/LWOMaterial.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -320,13 +320,10 @@ void LWOImporter::ConvertMaterial(const LWO::Surface& surf,aiMaterial* pcMat) // opacity ... either additive or default-blended, please if (0.0 != surf.mAdditiveTransparency) { - const int add = aiBlendMode_Additive; pcMat->AddProperty(&surf.mAdditiveTransparency,1,AI_MATKEY_OPACITY); pcMat->AddProperty(&add,1,AI_MATKEY_BLEND_FUNC); - } - - else if (10e10f != surf.mTransparency) { + } else if (10e10f != surf.mTransparency) { const int def = aiBlendMode_Default; const float f = 1.0f-surf.mTransparency; pcMat->AddProperty(&f,1,AI_MATKEY_OPACITY); diff --git a/third_party/libassimp/code/LWSLoader.cpp b/third_party/libassimp/code/LWS/LWSLoader.cpp similarity index 99% rename from third_party/libassimp/code/LWSLoader.cpp rename to third_party/libassimp/code/LWS/LWSLoader.cpp index 6f8cbe78de..b52cafa6d7 100644 --- a/third_party/libassimp/code/LWSLoader.cpp +++ b/third_party/libassimp/code/LWS/LWSLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -48,19 +48,20 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_LWS_IMPORTER -#include "LWSLoader.h" +#include "LWS/LWSLoader.h" +#include "PostProcessing/ConvertToLHProcess.h" +#include "Common/Importer.h" + #include #include - #include #include #include -#include "ConvertToLHProcess.h" -#include "Importer.h" #include #include #include #include + #include using namespace Assimp; diff --git a/third_party/libassimp/code/LWSLoader.h b/third_party/libassimp/code/LWS/LWSLoader.h similarity index 99% rename from third_party/libassimp/code/LWSLoader.h rename to third_party/libassimp/code/LWS/LWSLoader.h index 9f1636f21a..eed0491f3d 100644 --- a/third_party/libassimp/code/LWSLoader.h +++ b/third_party/libassimp/code/LWS/LWSLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -46,7 +46,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_LWSLOADER_H_INCLUDED #define AI_LWSLOADER_H_INCLUDED -#include "LWOFileData.h" +#include "LWO/LWOFileData.h" + #include #include diff --git a/third_party/libassimp/code/MD2FileData.h b/third_party/libassimp/code/MD2/MD2FileData.h similarity index 99% rename from third_party/libassimp/code/MD2FileData.h rename to third_party/libassimp/code/MD2/MD2FileData.h index 4b893bbb1a..9fcb8b0e2b 100644 --- a/third_party/libassimp/code/MD2FileData.h +++ b/third_party/libassimp/code/MD2/MD2FileData.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/MD2Loader.cpp b/third_party/libassimp/code/MD2/MD2Loader.cpp similarity index 99% rename from third_party/libassimp/code/MD2Loader.cpp rename to third_party/libassimp/code/MD2/MD2Loader.cpp index cfd5458e7a..7023c0fa32 100644 --- a/third_party/libassimp/code/MD2Loader.cpp +++ b/third_party/libassimp/code/MD2/MD2Loader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -344,7 +344,7 @@ void MD2Importer::InternReadFile( const std::string& pFile, if (pcSkins->name[0]) { aiString szString; - const size_t iLen = ::strlen(pcSkins->name); + const ai_uint32 iLen = (ai_uint32) ::strlen(pcSkins->name); ::memcpy(szString.data,pcSkins->name,iLen); szString.data[iLen] = '\0'; szString.length = iLen; diff --git a/third_party/libassimp/code/MD2Loader.h b/third_party/libassimp/code/MD2/MD2Loader.h similarity index 99% rename from third_party/libassimp/code/MD2Loader.h rename to third_party/libassimp/code/MD2/MD2Loader.h index f26b317368..a3863f366a 100644 --- a/third_party/libassimp/code/MD2Loader.h +++ b/third_party/libassimp/code/MD2/MD2Loader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/MD2NormalTable.h b/third_party/libassimp/code/MD2/MD2NormalTable.h similarity index 99% rename from third_party/libassimp/code/MD2NormalTable.h rename to third_party/libassimp/code/MD2/MD2NormalTable.h index dd2c837b40..f82b576832 100644 --- a/third_party/libassimp/code/MD2NormalTable.h +++ b/third_party/libassimp/code/MD2/MD2NormalTable.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/MD3FileData.h b/third_party/libassimp/code/MD3/MD3FileData.h similarity index 97% rename from third_party/libassimp/code/MD3FileData.h rename to third_party/libassimp/code/MD3/MD3FileData.h index 910813fc45..2acd6631f6 100644 --- a/third_party/libassimp/code/MD3FileData.h +++ b/third_party/libassimp/code/MD3/MD3FileData.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -59,7 +59,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include -namespace Assimp { +namespace Assimp { namespace MD3 { // to make it easier for us, we test the magic word against both "endianesses" @@ -303,12 +303,12 @@ inline void Vec3NormalToLatLng( const aiVector3D& p_vIn, uint16_t& p_iOut ) b = int(57.2957795f * ( std::acos( p_vIn[2] ) ) * ( 255.0f / 360.0f )); b &= 0xff; - ((unsigned char*)&p_iOut)[0] = b; // longitude - ((unsigned char*)&p_iOut)[1] = a; // latitude + ((unsigned char*)&p_iOut)[0] = (unsigned char) b; // longitude + ((unsigned char*)&p_iOut)[1] = (unsigned char) a; // latitude } } -} -} +} // Namespace MD3 +} // Namespace Assimp #endif // !! AI_MD3FILEHELPER_H_INC diff --git a/third_party/libassimp/code/MD3Loader.cpp b/third_party/libassimp/code/MD3/MD3Loader.cpp similarity index 97% rename from third_party/libassimp/code/MD3Loader.cpp rename to third_party/libassimp/code/MD3/MD3Loader.cpp index d12f2d5fd9..1e78b6e055 100644 --- a/third_party/libassimp/code/MD3Loader.cpp +++ b/third_party/libassimp/code/MD3/MD3Loader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -53,19 +53,21 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_MD3_IMPORTER -#include "MD3Loader.h" +#include "MD3/MD3Loader.h" +#include "Common/Importer.h" + #include #include #include #include -#include "Importer.h" #include -#include #include #include #include #include + #include +#include using namespace Assimp; @@ -258,10 +260,10 @@ bool Q3Shader::LoadSkin(SkinData& fill, const std::string& pFile,IOSystem* io) continue; fill.textures.push_back(SkinData::TextureEntry()); - SkinData::TextureEntry& s = fill.textures.back(); + SkinData::TextureEntry &entry = fill.textures.back(); - s.first = ss; - s.second = GetNextToken(buff); + entry.first = ss; + entry.second = GetNextToken(buff); } return true; } @@ -718,9 +720,7 @@ void MD3Importer::ConvertPath(const char* texture_name, const char* header_name, // ------------------------------------------------------------------------------------------------ // Imports the given file into the given scene structure. -void MD3Importer::InternReadFile( const std::string& pFile, - aiScene* pScene, IOSystem* pIOHandler) -{ +void MD3Importer::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) { mFile = pFile; mScene = pScene; mIOHandler = pIOHandler; @@ -730,11 +730,13 @@ void MD3Importer::InternReadFile( const std::string& pFile, std::string::size_type s = mFile.find_last_of("/\\"); if (s == std::string::npos) { s = 0; + } else { + ++s; + } + filename = mFile.substr(s), path = mFile.substr(0, s); + for (std::string::iterator it = filename.begin(); it != filename.end(); ++it) { + *it = static_cast( tolower(*it) ); } - else ++s; - filename = mFile.substr(s), path = mFile.substr(0,s); - for( std::string::iterator it = filename .begin(); it != filename.end(); ++it) - *it = tolower( *it); // Load multi-part model file, if necessary if (configHandleMP) { @@ -905,15 +907,15 @@ void MD3Importer::InternReadFile( const std::string& pFile, // Now search the current shader for a record with this name ( // excluding texture file extension) if (!shaders.blocks.empty()) { + std::string::size_type sh = convertedPath.find_last_of('.'); + if (sh == std::string::npos) { + sh = convertedPath.length(); + } - std::string::size_type s = convertedPath.find_last_of('.'); - if (s == std::string::npos) - s = convertedPath.length(); - - const std::string without_ext = convertedPath.substr(0,s); + const std::string without_ext = convertedPath.substr(0,sh); std::list< Q3Shader::ShaderDataBlock >::const_iterator dit = std::find(shaders.blocks.begin(),shaders.blocks.end(),without_ext); if (dit != shaders.blocks.end()) { - // Hurra, wir haben einen. Tolle Sache. + // We made it! shader = &*dit; ASSIMP_LOG_INFO("Found shader record for " +without_ext ); } else { @@ -945,8 +947,7 @@ void MD3Importer::InternReadFile( const std::string& pFile, aiString szString; if (convertedPath.length()) { szString.Set(convertedPath); - } - else { + } else { ASSIMP_LOG_WARN("Texture file name has zero length. Using default name"); szString.Set("dummy_texture.bmp"); } @@ -955,8 +956,7 @@ void MD3Importer::InternReadFile( const std::string& pFile, // prevent transparency by default int no_alpha = aiTextureFlags_IgnoreAlpha; pcHelper->AddProperty(&no_alpha,1,AI_MATKEY_TEXFLAGS_DIFFUSE(0)); - } - else { + } else { Q3Shader::ConvertShaderToMaterial(pcHelper,*shader); } @@ -1026,7 +1026,7 @@ void MD3Importer::InternReadFile( const std::string& pFile, if (!shader || shader->cull == Q3Shader::CULL_CW) { std::swap(pcMesh->mFaces[i].mIndices[2],pcMesh->mFaces[i].mIndices[1]); } - pcTriangles++; + ++pcTriangles; } // Go to the next surface @@ -1042,8 +1042,9 @@ void MD3Importer::InternReadFile( const std::string& pFile, } } - if (!pScene->mNumMeshes) + if (!pScene->mNumMeshes) { throw DeadlyImportError( "MD3: File contains no valid mesh"); + } pScene->mNumMaterials = iNumMaterials; // Now we need to generate an empty node graph @@ -1057,7 +1058,6 @@ void MD3Importer::InternReadFile( const std::string& pFile, pScene->mRootNode->mChildren = new aiNode*[pcHeader->NUM_TAGS]; for (unsigned int i = 0; i < pcHeader->NUM_TAGS; ++i, ++pcTags) { - aiNode* nd = pScene->mRootNode->mChildren[i] = new aiNode(); nd->mName.Set((const char*)pcTags->NAME); nd->mParent = pScene->mRootNode; @@ -1085,8 +1085,12 @@ void MD3Importer::InternReadFile( const std::string& pFile, pScene->mRootNode->mMeshes[i] = i; // Now rotate the whole scene 90 degrees around the x axis to convert to internal coordinate system - pScene->mRootNode->mTransformation = aiMatrix4x4(1.f,0.f,0.f,0.f, - 0.f,0.f,1.f,0.f,0.f,-1.f,0.f,0.f,0.f,0.f,0.f,1.f); + pScene->mRootNode->mTransformation = aiMatrix4x4( + 1.f,0.f,0.f,0.f, + 0.f,0.f,1.f,0.f, + 0.f,-1.f,0.f,0.f, + 0.f,0.f,0.f,1.f + ); } #endif // !! ASSIMP_BUILD_NO_MD3_IMPORTER diff --git a/third_party/libassimp/code/MD3Loader.h b/third_party/libassimp/code/MD3/MD3Loader.h similarity index 99% rename from third_party/libassimp/code/MD3Loader.h rename to third_party/libassimp/code/MD3/MD3Loader.h index 8ac3cdc682..01b8402283 100644 --- a/third_party/libassimp/code/MD3Loader.h +++ b/third_party/libassimp/code/MD3/MD3Loader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/MD4FileData.h b/third_party/libassimp/code/MD4/MD4FileData.h similarity index 100% rename from third_party/libassimp/code/MD4FileData.h rename to third_party/libassimp/code/MD4/MD4FileData.h diff --git a/third_party/libassimp/code/MD5Loader.cpp b/third_party/libassimp/code/MD5/MD5Loader.cpp similarity index 97% rename from third_party/libassimp/code/MD5Loader.cpp rename to third_party/libassimp/code/MD5/MD5Loader.cpp index a4285ba036..a4aed8d70f 100644 --- a/third_party/libassimp/code/MD5Loader.cpp +++ b/third_party/libassimp/code/MD5/MD5Loader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -53,6 +53,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "MD5Loader.h" #include #include +#include #include #include #include @@ -64,7 +65,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using namespace Assimp; // Minimum weight value. Weights inside [-n ... n] are ignored -#define AI_MD5_WEIGHT_EPSILON 1e-5f +#define AI_MD5_WEIGHT_EPSILON Math::getEpsilon() static const aiImporterDesc desc = { @@ -443,10 +444,10 @@ void MD5Importer::LoadMD5MeshFile () for (MD5::VertexList::const_iterator iter = meshSrc.mVertices.begin();iter != meshSrc.mVertices.end();++iter,++pv) { for (unsigned int jub = (*iter).mFirstWeight, w = jub; w < jub + (*iter).mNumWeights;++w) { - MD5::WeightDesc& desc = meshSrc.mWeights[w]; + MD5::WeightDesc& weightDesc = meshSrc.mWeights[w]; /* FIX for some invalid exporters */ - if (!(desc.mWeight < AI_MD5_WEIGHT_EPSILON && desc.mWeight >= -AI_MD5_WEIGHT_EPSILON )) - ++piCount[desc.mBone]; + if (!(weightDesc.mWeight < AI_MD5_WEIGHT_EPSILON && weightDesc.mWeight >= -AI_MD5_WEIGHT_EPSILON )) + ++piCount[weightDesc.mBone]; } } @@ -493,20 +494,20 @@ void MD5Importer::LoadMD5MeshFile () if (w >= meshSrc.mWeights.size()) throw DeadlyImportError("MD5MESH: Invalid weight index"); - MD5::WeightDesc& desc = meshSrc.mWeights[w]; - if ( desc.mWeight < AI_MD5_WEIGHT_EPSILON && desc.mWeight >= -AI_MD5_WEIGHT_EPSILON) { + MD5::WeightDesc& weightDesc = meshSrc.mWeights[w]; + if ( weightDesc.mWeight < AI_MD5_WEIGHT_EPSILON && weightDesc.mWeight >= -AI_MD5_WEIGHT_EPSILON) { continue; } - const ai_real fNewWeight = desc.mWeight / fSum; + const ai_real fNewWeight = weightDesc.mWeight / fSum; // transform the local position into worldspace - MD5::BoneDesc& boneSrc = meshParser.mJoints[desc.mBone]; - const aiVector3D v = boneSrc.mRotationQuatConverted.Rotate (desc.vOffsetPosition); + MD5::BoneDesc& boneSrc = meshParser.mJoints[weightDesc.mBone]; + const aiVector3D v = boneSrc.mRotationQuatConverted.Rotate (weightDesc.vOffsetPosition); // use the original weight to compute the vertex position // (some MD5s seem to depend on the invalid weight values ...) - *pv += ((boneSrc.mPositionXYZ+v)* (ai_real)desc.mWeight); + *pv += ((boneSrc.mPositionXYZ+v)* (ai_real)weightDesc.mWeight); aiBone* bone = mesh->mBones[boneSrc.mMap]; *bone->mWeights++ = aiVertexWeight((unsigned int)(pv-mesh->mVertices),fNewWeight); diff --git a/third_party/libassimp/code/MD5Loader.h b/third_party/libassimp/code/MD5/MD5Loader.h similarity index 99% rename from third_party/libassimp/code/MD5Loader.h rename to third_party/libassimp/code/MD5/MD5Loader.h index 1ba5fea68b..e15cc3fb9c 100644 --- a/third_party/libassimp/code/MD5Loader.h +++ b/third_party/libassimp/code/MD5/MD5Loader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/MD5Parser.cpp b/third_party/libassimp/code/MD5/MD5Parser.cpp similarity index 99% rename from third_party/libassimp/code/MD5Parser.cpp rename to third_party/libassimp/code/MD5/MD5Parser.cpp index 6f942228c9..37490212fb 100644 --- a/third_party/libassimp/code/MD5Parser.cpp +++ b/third_party/libassimp/code/MD5/MD5Parser.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -47,16 +47,15 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // internal headers -#include "MD5Loader.h" -#include "MaterialSystem.h" +#include "MD5/MD5Loader.h" +#include "Material/MaterialSystem.h" + #include #include #include #include #include - - using namespace Assimp; using namespace Assimp::MD5; @@ -236,7 +235,7 @@ bool MD5Parser::ParseSection(Section& out) const char* szStart = ++sz; \ while('\"'!=*sz)++sz; \ const char* szEnd = (sz++); \ - out.length = (size_t)(szEnd - szStart); \ + out.length = (ai_uint32) (szEnd - szStart); \ ::memcpy(out.data,szStart,out.length); \ out.data[out.length] = '\0'; // ------------------------------------------------------------------------------------------------ diff --git a/third_party/libassimp/code/MD5Parser.h b/third_party/libassimp/code/MD5/MD5Parser.h similarity index 99% rename from third_party/libassimp/code/MD5Parser.h rename to third_party/libassimp/code/MD5/MD5Parser.h index 853268424e..f7ff5303f4 100644 --- a/third_party/libassimp/code/MD5Parser.h +++ b/third_party/libassimp/code/MD5/MD5Parser.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/MDCFileData.h b/third_party/libassimp/code/MDC/MDCFileData.h similarity index 99% rename from third_party/libassimp/code/MDCFileData.h rename to third_party/libassimp/code/MDC/MDCFileData.h index c599a930ac..0524731587 100644 --- a/third_party/libassimp/code/MDCFileData.h +++ b/third_party/libassimp/code/MDC/MDCFileData.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/MDCLoader.cpp b/third_party/libassimp/code/MDC/MDCLoader.cpp similarity index 99% rename from third_party/libassimp/code/MDCLoader.cpp rename to third_party/libassimp/code/MDC/MDCLoader.cpp index 03b3336def..084ec60249 100644 --- a/third_party/libassimp/code/MDCLoader.cpp +++ b/third_party/libassimp/code/MDC/MDCLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -47,16 +47,17 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_MDC_IMPORTER // internal headers -#include "MDCLoader.h" -#include "MD3FileData.h" -#include "MDCNormalTable.h" // shouldn't be included by other units +#include "MDC/MDCLoader.h" +#include "MD3/MD3FileData.h" +#include "MDC/MDCNormalTable.h" // shouldn't be included by other units + #include #include #include #include #include -#include +#include using namespace Assimp; using namespace Assimp::MDC; diff --git a/third_party/libassimp/code/MDCLoader.h b/third_party/libassimp/code/MDC/MDCLoader.h similarity index 99% rename from third_party/libassimp/code/MDCLoader.h rename to third_party/libassimp/code/MDC/MDCLoader.h index 5bbe2b6668..a21b8a55ac 100644 --- a/third_party/libassimp/code/MDCLoader.h +++ b/third_party/libassimp/code/MDC/MDCLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/MDCNormalTable.h b/third_party/libassimp/code/MDC/MDCNormalTable.h similarity index 100% rename from third_party/libassimp/code/MDCNormalTable.h rename to third_party/libassimp/code/MDC/MDCNormalTable.h diff --git a/third_party/libassimp/code/MDLDefaultColorMap.h b/third_party/libassimp/code/MDL/MDLDefaultColorMap.h similarity index 99% rename from third_party/libassimp/code/MDLDefaultColorMap.h rename to third_party/libassimp/code/MDL/MDLDefaultColorMap.h index b96a60a06a..58f6428841 100644 --- a/third_party/libassimp/code/MDLDefaultColorMap.h +++ b/third_party/libassimp/code/MDL/MDLDefaultColorMap.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/MDLFileData.h b/third_party/libassimp/code/MDL/MDLFileData.h similarity index 99% rename from third_party/libassimp/code/MDLFileData.h rename to third_party/libassimp/code/MDL/MDLFileData.h index f9be6761b7..f33a57731f 100644 --- a/third_party/libassimp/code/MDLFileData.h +++ b/third_party/libassimp/code/MDL/MDLFileData.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/MDLLoader.cpp b/third_party/libassimp/code/MDL/MDLLoader.cpp similarity index 99% rename from third_party/libassimp/code/MDLLoader.cpp rename to third_party/libassimp/code/MDL/MDLLoader.cpp index eb067a1c94..9c9ce23300 100644 --- a/third_party/libassimp/code/MDLLoader.cpp +++ b/third_party/libassimp/code/MDL/MDLLoader.cpp @@ -3,9 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team - - +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -50,11 +48,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_MDL_IMPORTER -#include "MDLLoader.h" +#include "MDL/MDLLoader.h" +#include "MDL/MDLDefaultColorMap.h" +#include "MD2/MD2FileData.h" + #include #include -#include "MDLDefaultColorMap.h" -#include "MD2FileData.h" #include #include #include @@ -93,23 +92,24 @@ static const aiImporterDesc desc = { // ------------------------------------------------------------------------------------------------ // Constructor to be privately used by Importer MDLImporter::MDLImporter() - : configFrameID(), - mBuffer(), - iGSFileVersion(), - pIOHandler(), - pScene(), - iFileSize() -{} +: configFrameID() +, mBuffer() +, iGSFileVersion() +, pIOHandler() +, pScene() +, iFileSize() { + // empty +} // ------------------------------------------------------------------------------------------------ // Destructor, private as well -MDLImporter::~MDLImporter() -{} +MDLImporter::~MDLImporter() { + // empty +} // ------------------------------------------------------------------------------------------------ // Returns whether the class can handle the format of the given file. -bool MDLImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const -{ +bool MDLImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const { const std::string extension = GetExtension(pFile); // if check for extension is not enough, check for the magic tokens @@ -403,23 +403,15 @@ void MDLImporter::InternReadFile_Quake1() { // now get a pointer to the first frame in the file BE_NCONST MDL::Frame* pcFrames = (BE_NCONST MDL::Frame*)szCurrent; - BE_NCONST MDL::SimpleFrame* pcFirstFrame; + MDL::SimpleFrame* pcFirstFrame; if (0 == pcFrames->type) { // get address of single frame - pcFirstFrame = &pcFrames->frame; + pcFirstFrame =( MDL::SimpleFrame*) &pcFrames->frame; } else { // get the first frame in the group - -#if 1 - // FIXME: the cast is wrong and cause a warning on clang 5.0 - // disable this code for now, fix it later - ai_assert(false && "Bad pointer cast"); - pcFirstFrame = nullptr; // Workaround: msvc++ C4703 error -#else - BE_NCONST MDL::GroupFrame* pcFrames2 = (BE_NCONST MDL::GroupFrame*)pcFrames; - pcFirstFrame = (BE_NCONST MDL::SimpleFrame*)(&pcFrames2->time + pcFrames->type); -#endif + BE_NCONST MDL::GroupFrame* pcFrames2 = (BE_NCONST MDL::GroupFrame*) pcFrames; + pcFirstFrame = &(pcFrames2->frames[0]); } BE_NCONST MDL::Vertex* pcVertices = (BE_NCONST MDL::Vertex*) ((pcFirstFrame->name) + sizeof(pcFirstFrame->name)); VALIDATE_FILE_SIZE((const unsigned char*)(pcVertices + pcHeader->num_verts)); diff --git a/third_party/libassimp/code/MDLLoader.h b/third_party/libassimp/code/MDL/MDLLoader.h similarity index 99% rename from third_party/libassimp/code/MDLLoader.h rename to third_party/libassimp/code/MDL/MDLLoader.h index f1504beea9..c5ebac024c 100644 --- a/third_party/libassimp/code/MDLLoader.h +++ b/third_party/libassimp/code/MDL/MDLLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -50,7 +50,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include "MDLFileData.h" -#include "HalfLifeFileData.h" +#include "HMP/HalfLifeFileData.h" struct aiNode; struct aiTexture; @@ -89,16 +89,12 @@ public: MDLImporter(); ~MDLImporter(); - -public: - // ------------------------------------------------------------------- /** Returns whether the class can handle the format of the given file. * See BaseImporter::CanRead() for details. */ bool CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const; - // ------------------------------------------------------------------- /** Called prior to ReadFile(). * The function is a request to the importer to update its configuration @@ -107,8 +103,6 @@ public: void SetupProperties(const Importer* pImp); protected: - - // ------------------------------------------------------------------- /** Return importer meta information. * See #BaseImporter::GetInfo for the details @@ -122,8 +116,6 @@ protected: void InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler); -protected: - // ------------------------------------------------------------------- /** Import a quake 1 MDL file (IDPO) */ @@ -154,7 +146,6 @@ protected: void SizeCheck(const void* szPos); void SizeCheck(const void* szPos, const char* szFile, unsigned int iLine); - // ------------------------------------------------------------------- /** Validate the header data structure of a game studio MDL7 file * \param pcHeader Input header to be validated @@ -167,7 +158,6 @@ protected: */ void ValidateHeader_Quake1(const MDL::Header* pcHeader); - // ------------------------------------------------------------------- /** Try to load a palette from the current directory (colormap.lmp) * If it is not found the default palette of Quake1 is returned @@ -179,9 +169,8 @@ protected: */ void FreePalette(const unsigned char* pszColorMap); - // ------------------------------------------------------------------- - /** Load a paletized texture from the file and convert it to 32bpp + /** Load a palletized texture from the file and convert it to 32bpp */ void CreateTextureARGB8_3DGS_MDL3(const unsigned char* szData); @@ -195,7 +184,6 @@ protected: unsigned int iType, unsigned int* piSkip); - // ------------------------------------------------------------------- /** Used to load textures from MDL5 * \param szData Input data @@ -206,7 +194,6 @@ protected: unsigned int iType, unsigned int* piSkip); - // ------------------------------------------------------------------- /** Checks whether a texture can be replaced with a single color * This is useful for all file formats before MDL7 (all those @@ -218,14 +205,12 @@ protected: */ aiColor4D ReplaceTextureWithColor(const aiTexture* pcTexture); - // ------------------------------------------------------------------- /** Converts the absolute texture coordinates in MDL5 files to * relative in a range between 0 and 1 */ void CalculateUVCoordinates_MDL5(); - // ------------------------------------------------------------------- /** Read an UV coordinate from the file. If the file format is not * MDL5, the function calculates relative texture coordinates @@ -245,7 +230,6 @@ protected: */ void SetupMaterialProperties_3DGS_MDL5_Quake1( ); - // ------------------------------------------------------------------- /** Parse a skin lump in a MDL7/HMP7 file with all of its features * variant 1: Current cursor position is the beginning of the skin header diff --git a/third_party/libassimp/code/MDLMaterialLoader.cpp b/third_party/libassimp/code/MDL/MDLMaterialLoader.cpp similarity index 99% rename from third_party/libassimp/code/MDLMaterialLoader.cpp rename to third_party/libassimp/code/MDL/MDLMaterialLoader.cpp index 2c21b188be..0a196761f4 100644 --- a/third_party/libassimp/code/MDLMaterialLoader.cpp +++ b/third_party/libassimp/code/MDL/MDLMaterialLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/MMDCpp14.h b/third_party/libassimp/code/MMD/MMDCpp14.h similarity index 98% rename from third_party/libassimp/code/MMDCpp14.h rename to third_party/libassimp/code/MMD/MMDCpp14.h index 5ec2fd9753..638b0bfd2f 100644 --- a/third_party/libassimp/code/MMDCpp14.h +++ b/third_party/libassimp/code/MMD/MMDCpp14.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/MMDImporter.cpp b/third_party/libassimp/code/MMD/MMDImporter.cpp similarity index 98% rename from third_party/libassimp/code/MMDImporter.cpp rename to third_party/libassimp/code/MMD/MMDImporter.cpp index 84b9e35a6b..e7744e4cd0 100644 --- a/third_party/libassimp/code/MMDImporter.cpp +++ b/third_party/libassimp/code/MMD/MMDImporter.cpp @@ -41,15 +41,17 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_MMD_IMPORTER -#include "MMDImporter.h" -#include "MMDPmdParser.h" -#include "MMDPmxParser.h" -#include "MMDVmdParser.h" -#include "ConvertToLHProcess.h" +#include "MMD/MMDImporter.h" +#include "MMD/MMDPmdParser.h" +#include "MMD/MMDPmxParser.h" +#include "MMD/MMDVmdParser.h" +#include "PostProcessing/ConvertToLHProcess.h" + #include #include #include #include + #include #include #include diff --git a/third_party/libassimp/code/MMDImporter.h b/third_party/libassimp/code/MMD/MMDImporter.h similarity index 100% rename from third_party/libassimp/code/MMDImporter.h rename to third_party/libassimp/code/MMD/MMDImporter.h diff --git a/third_party/libassimp/code/MMDPmdParser.h b/third_party/libassimp/code/MMD/MMDPmdParser.h similarity index 99% rename from third_party/libassimp/code/MMDPmdParser.h rename to third_party/libassimp/code/MMD/MMDPmdParser.h index d61a355fbe..d2f2224aa1 100644 --- a/third_party/libassimp/code/MMDPmdParser.h +++ b/third_party/libassimp/code/MMD/MMDPmdParser.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/MMDPmxParser.cpp b/third_party/libassimp/code/MMD/MMDPmxParser.cpp similarity index 99% rename from third_party/libassimp/code/MMDPmxParser.cpp rename to third_party/libassimp/code/MMD/MMDPmxParser.cpp index 2c5bd9a8db..80f0986dd7 100644 --- a/third_party/libassimp/code/MMDPmxParser.cpp +++ b/third_party/libassimp/code/MMD/MMDPmxParser.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -42,7 +42,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include "MMDPmxParser.h" #include -#include "../contrib/utf8cpp/source/utf8.h" +#ifdef ASSIMP_USE_HUNTER +# include +#else +# include "../contrib/utf8cpp/source/utf8.h" +#endif #include namespace pmx diff --git a/third_party/libassimp/code/MMDPmxParser.h b/third_party/libassimp/code/MMD/MMDPmxParser.h similarity index 99% rename from third_party/libassimp/code/MMDPmxParser.h rename to third_party/libassimp/code/MMD/MMDPmxParser.h index 43cad5899f..cf523a1298 100644 --- a/third_party/libassimp/code/MMDPmxParser.h +++ b/third_party/libassimp/code/MMD/MMDPmxParser.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/MMDVmdParser.h b/third_party/libassimp/code/MMD/MMDVmdParser.h similarity index 99% rename from third_party/libassimp/code/MMDVmdParser.h rename to third_party/libassimp/code/MMD/MMDVmdParser.h index 600959e944..947c3a2422 100644 --- a/third_party/libassimp/code/MMDVmdParser.h +++ b/third_party/libassimp/code/MMD/MMDVmdParser.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/MS3DLoader.cpp b/third_party/libassimp/code/MS3D/MS3DLoader.cpp similarity index 99% rename from third_party/libassimp/code/MS3DLoader.cpp rename to third_party/libassimp/code/MS3D/MS3DLoader.cpp index c659d2ec7f..c0d0eddbee 100644 --- a/third_party/libassimp/code/MS3DLoader.cpp +++ b/third_party/libassimp/code/MS3D/MS3DLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/MS3DLoader.h b/third_party/libassimp/code/MS3D/MS3DLoader.h similarity index 99% rename from third_party/libassimp/code/MS3DLoader.h rename to third_party/libassimp/code/MS3D/MS3DLoader.h index 2efa3be5fb..3e39dc79fe 100644 --- a/third_party/libassimp/code/MS3DLoader.h +++ b/third_party/libassimp/code/MS3D/MS3DLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/MaterialSystem.cpp b/third_party/libassimp/code/Material/MaterialSystem.cpp similarity index 95% rename from third_party/libassimp/code/MaterialSystem.cpp rename to third_party/libassimp/code/Material/MaterialSystem.cpp index e9ca475fba..ecdf9942c4 100644 --- a/third_party/libassimp/code/MaterialSystem.cpp +++ b/third_party/libassimp/code/Material/MaterialSystem.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -96,12 +96,12 @@ aiReturn aiGetMaterialFloatArray(const aiMaterial* pMat, ai_real* pOut, unsigned int* pMax) { - ai_assert( pOut != NULL ); - ai_assert( pMat != NULL ); + ai_assert( pOut != nullptr ); + ai_assert( pMat != nullptr ); const aiMaterialProperty* prop; aiGetMaterialProperty(pMat,pKey,type,index, (const aiMaterialProperty**) &prop); - if (!prop) { + if ( nullptr == prop) { return AI_FAILURE; } @@ -112,9 +112,11 @@ aiReturn aiGetMaterialFloatArray(const aiMaterial* pMat, if (pMax) { iWrite = std::min(*pMax,iWrite); ; } - for (unsigned int a = 0; a < iWrite;++a) { - pOut[a] = static_cast ( reinterpret_cast(prop->mData)[a] ); + + for (unsigned int a = 0; a < iWrite; ++a) { + pOut[ a ] = static_cast ( reinterpret_cast(prop->mData)[a] ); } + if (pMax) { *pMax = iWrite; } @@ -543,23 +545,7 @@ aiReturn aiMaterial::AddProperty (const aiString* pInput, unsigned int type, unsigned int index) { - // We don't want to add the whole buffer .. write a 32 bit length - // prefix followed by the zero-terminated UTF8 string. - // (HACK) I don't want to break the ABI now, but we definitely - // ought to change aiString::mLength to uint32_t one day. - if (sizeof(size_t) == 8) { - aiString copy = *pInput; - uint32_t* s = reinterpret_cast(©.length); - s[1] = static_cast(pInput->length); - - return AddBinaryProperty(s+1, - static_cast(pInput->length+1+4), - pKey, - type, - index, - aiPTI_String); - } - ai_assert(sizeof(size_t)==4); + ai_assert(sizeof(ai_uint32)==4); return AddBinaryProperty(pInput, static_cast(pInput->length+1+4), pKey, diff --git a/third_party/libassimp/code/MaterialSystem.h b/third_party/libassimp/code/Material/MaterialSystem.h similarity index 98% rename from third_party/libassimp/code/MaterialSystem.h rename to third_party/libassimp/code/Material/MaterialSystem.h index d6f2cea468..67d53578cb 100644 --- a/third_party/libassimp/code/MaterialSystem.h +++ b/third_party/libassimp/code/Material/MaterialSystem.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/NDOLoader.cpp b/third_party/libassimp/code/NDO/NDOLoader.cpp similarity index 99% rename from third_party/libassimp/code/NDOLoader.cpp rename to third_party/libassimp/code/NDO/NDOLoader.cpp index 17c9e135b4..d33f40c758 100644 --- a/third_party/libassimp/code/NDOLoader.cpp +++ b/third_party/libassimp/code/NDO/NDOLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/NDOLoader.h b/third_party/libassimp/code/NDO/NDOLoader.h similarity index 100% rename from third_party/libassimp/code/NDOLoader.h rename to third_party/libassimp/code/NDO/NDOLoader.h diff --git a/third_party/libassimp/code/NFFLoader.cpp b/third_party/libassimp/code/NFF/NFFLoader.cpp similarity index 99% rename from third_party/libassimp/code/NFFLoader.cpp rename to third_party/libassimp/code/NFF/NFFLoader.cpp index 1c7283db6d..10a7d1aff6 100644 --- a/third_party/libassimp/code/NFFLoader.cpp +++ b/third_party/libassimp/code/NFF/NFFLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/NFFLoader.h b/third_party/libassimp/code/NFF/NFFLoader.h similarity index 99% rename from third_party/libassimp/code/NFFLoader.h rename to third_party/libassimp/code/NFF/NFFLoader.h index 1e3f0bd26f..bc4840e14f 100644 --- a/third_party/libassimp/code/NFFLoader.h +++ b/third_party/libassimp/code/NFF/NFFLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/OFFLoader.cpp b/third_party/libassimp/code/OFF/OFFLoader.cpp similarity index 99% rename from third_party/libassimp/code/OFFLoader.cpp rename to third_party/libassimp/code/OFF/OFFLoader.cpp index a72e6d9d41..afd44a5399 100644 --- a/third_party/libassimp/code/OFFLoader.cpp +++ b/third_party/libassimp/code/OFF/OFFLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/OFFLoader.h b/third_party/libassimp/code/OFF/OFFLoader.h similarity index 98% rename from third_party/libassimp/code/OFFLoader.h rename to third_party/libassimp/code/OFF/OFFLoader.h index ed1ed98c1b..3fca77e1b9 100644 --- a/third_party/libassimp/code/OFFLoader.h +++ b/third_party/libassimp/code/OFF/OFFLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/ObjExporter.cpp b/third_party/libassimp/code/Obj/ObjExporter.cpp similarity index 99% rename from third_party/libassimp/code/ObjExporter.cpp rename to third_party/libassimp/code/Obj/ObjExporter.cpp index 1542efebf7..0a0dbd62c0 100644 --- a/third_party/libassimp/code/ObjExporter.cpp +++ b/third_party/libassimp/code/Obj/ObjExporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -126,9 +126,9 @@ ObjExporter::ObjExporter(const char* _filename, const aiScene* pScene, bool noMt // make sure that all formatting happens using the standard, C locale and not the user's current locale const std::locale& l = std::locale("C"); mOutput.imbue(l); - mOutput.precision(16); + mOutput.precision(ASSIMP_AI_REAL_TEXT_PRECISION); mOutputMat.imbue(l); - mOutputMat.precision(16); + mOutputMat.precision(ASSIMP_AI_REAL_TEXT_PRECISION); WriteGeometryFile(noMtl); if ( !noMtl ) { diff --git a/third_party/libassimp/code/ObjExporter.h b/third_party/libassimp/code/Obj/ObjExporter.h similarity index 99% rename from third_party/libassimp/code/ObjExporter.h rename to third_party/libassimp/code/Obj/ObjExporter.h index bd745b5939..0d2b48d6b8 100644 --- a/third_party/libassimp/code/ObjExporter.h +++ b/third_party/libassimp/code/Obj/ObjExporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/ObjFileData.h b/third_party/libassimp/code/Obj/ObjFileData.h similarity index 98% rename from third_party/libassimp/code/ObjFileData.h rename to third_party/libassimp/code/Obj/ObjFileData.h index 38786e6f48..a2d9f2cc79 100644 --- a/third_party/libassimp/code/ObjFileData.h +++ b/third_party/libassimp/code/Obj/ObjFileData.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -281,6 +281,8 @@ struct Model { std::string m_strActiveGroup; //! Vector with generated texture coordinates std::vector m_TextureCoord; + //! Maximum dimension of texture coordinates + unsigned int m_TextureCoordDim; //! Current mesh instance Mesh *m_pCurrentMesh; //! Vector with stored meshes @@ -296,6 +298,7 @@ struct Model { m_pDefaultMaterial(NULL), m_pGroupFaceIDs(NULL), m_strActiveGroup(""), + m_TextureCoordDim(0), m_pCurrentMesh(NULL) { // empty diff --git a/third_party/libassimp/code/ObjFileImporter.cpp b/third_party/libassimp/code/Obj/ObjFileImporter.cpp similarity index 93% rename from third_party/libassimp/code/ObjFileImporter.cpp rename to third_party/libassimp/code/Obj/ObjFileImporter.cpp index 6fd48cfa10..26cc6d1f9c 100644 --- a/third_party/libassimp/code/ObjFileImporter.cpp +++ b/third_party/libassimp/code/Obj/ObjFileImporter.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -79,10 +79,7 @@ using namespace std; ObjFileImporter::ObjFileImporter() : m_Buffer() , m_pRootObject( nullptr ) -, m_strAbsPath( "" ) { - DefaultIOSystem io; - m_strAbsPath = io.getOsSeparator(); -} +, m_strAbsPath( std::string(1, DefaultIOSystem().getOsSeparator()) ) {} // ------------------------------------------------------------------------------------------------ // Destructor. @@ -144,38 +141,6 @@ void ObjFileImporter::InternReadFile( const std::string &file, aiScene* pScene, modelName = file; } - // This next stage takes ~ 1/3th of the total readFile task - // so should amount for 1/3th of the progress - // only update every 100KB or it'll be too slow - /*unsigned int progress = 0; - unsigned int progressCounter = 0; - const unsigned int updateProgressEveryBytes = 100 * 1024; - const unsigned int progressTotal = static_cast(3*m_Buffer.size()/updateProgressEveryBytes);*/ - // process all '\' - /*std::vector ::iterator iter = m_Buffer.begin(); - while (iter != m_Buffer.end()) - { - if (*iter == '\\') - { - // remove '\' - iter = m_Buffer.erase(iter); - // remove next character - while (*iter == '\r' || *iter == '\n') - iter = m_Buffer.erase(iter); - } - else - ++iter; - - if (++progressCounter >= updateProgressEveryBytes) - { - m_progress->UpdateFileRead(++progress, progressTotal); - progressCounter = 0; - } - }*/ - - // 1/3rd progress - m_progress->UpdateFileRead(1, 3); - // parse the file into a temporary representation ObjFileParser parser( streamedBuffer, modelName, pIOHandler, m_progress, file); @@ -474,11 +439,12 @@ void ObjFileImporter::createVertexArray(const ObjFile::Model* pModel, // Allocate buffer for texture coordinates if ( !pModel->m_TextureCoord.empty() && pObjMesh->m_uiUVCoordinates[0] ) { - pMesh->mNumUVComponents[ 0 ] = 2; + pMesh->mNumUVComponents[ 0 ] = pModel->m_TextureCoordDim; pMesh->mTextureCoords[ 0 ] = new aiVector3D[ pMesh->mNumVertices ]; } // Copy vertices, normals and textures into aiMesh instance + bool normalsok = true, uvok = true; unsigned int newIndex = 0, outIndex = 0; for ( size_t index=0; index < pObjMesh->m_Faces.size(); index++ ) { // Get source face @@ -498,12 +464,16 @@ void ObjFileImporter::createVertexArray(const ObjFile::Model* pModel, pMesh->mVertices[ newIndex ] = pModel->m_Vertices[ vertex ]; // Copy all normals - if ( !pModel->m_Normals.empty() && vertexIndex < pSourceFace->m_normals.size()) { + if ( normalsok && !pModel->m_Normals.empty() && vertexIndex < pSourceFace->m_normals.size()) { const unsigned int normal = pSourceFace->m_normals.at( vertexIndex ); - if ( normal >= pModel->m_Normals.size() ) { - throw DeadlyImportError( "OBJ: vertex normal index out of range" ); + if ( normal >= pModel->m_Normals.size() ) + { + normalsok = false; + } + else + { + pMesh->mNormals[ newIndex ] = pModel->m_Normals[ normal ]; } - pMesh->mNormals[ newIndex ] = pModel->m_Normals[ normal ]; } // Copy all vertex colors @@ -514,15 +484,19 @@ void ObjFileImporter::createVertexArray(const ObjFile::Model* pModel, } // Copy all texture coordinates - if ( !pModel->m_TextureCoord.empty() && vertexIndex < pSourceFace->m_texturCoords.size()) + if ( uvok && !pModel->m_TextureCoord.empty() && vertexIndex < pSourceFace->m_texturCoords.size()) { const unsigned int tex = pSourceFace->m_texturCoords.at( vertexIndex ); if ( tex >= pModel->m_TextureCoord.size() ) - throw DeadlyImportError("OBJ: texture coordinate index out of range"); - - const aiVector3D &coord3d = pModel->m_TextureCoord[ tex ]; - pMesh->mTextureCoords[ 0 ][ newIndex ] = aiVector3D( coord3d.x, coord3d.y, coord3d.z ); + { + uvok = false; + } + else + { + const aiVector3D &coord3d = pModel->m_TextureCoord[ tex ]; + pMesh->mTextureCoords[ 0 ][ newIndex ] = aiVector3D( coord3d.x, coord3d.y, coord3d.z ); + } } // Get destination face @@ -566,6 +540,18 @@ void ObjFileImporter::createVertexArray(const ObjFile::Model* pModel, ++newIndex; } } + + if (!normalsok) + { + delete [] pMesh->mNormals; + pMesh->mNormals = nullptr; + } + + if (!uvok) + { + delete [] pMesh->mTextureCoords[0]; + pMesh->mTextureCoords[0] = nullptr; + } } // ------------------------------------------------------------------------------------------------ diff --git a/third_party/libassimp/code/ObjFileImporter.h b/third_party/libassimp/code/Obj/ObjFileImporter.h similarity index 99% rename from third_party/libassimp/code/ObjFileImporter.h rename to third_party/libassimp/code/Obj/ObjFileImporter.h index f564fe22bb..0df2ef7315 100644 --- a/third_party/libassimp/code/ObjFileImporter.h +++ b/third_party/libassimp/code/Obj/ObjFileImporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/ObjFileMtlImporter.cpp b/third_party/libassimp/code/Obj/ObjFileMtlImporter.cpp similarity index 99% rename from third_party/libassimp/code/ObjFileMtlImporter.cpp rename to third_party/libassimp/code/Obj/ObjFileMtlImporter.cpp index 16bde1b439..dd9cc3ce23 100644 --- a/third_party/libassimp/code/ObjFileMtlImporter.cpp +++ b/third_party/libassimp/code/Obj/ObjFileMtlImporter.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/ObjFileMtlImporter.h b/third_party/libassimp/code/Obj/ObjFileMtlImporter.h similarity index 99% rename from third_party/libassimp/code/ObjFileMtlImporter.h rename to third_party/libassimp/code/Obj/ObjFileMtlImporter.h index d6a7b1f1ad..7319523598 100644 --- a/third_party/libassimp/code/ObjFileMtlImporter.h +++ b/third_party/libassimp/code/Obj/ObjFileMtlImporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/ObjFileParser.cpp b/third_party/libassimp/code/Obj/ObjFileParser.cpp similarity index 95% rename from third_party/libassimp/code/ObjFileParser.cpp rename to third_party/libassimp/code/Obj/ObjFileParser.cpp index 7630127fab..699aafe6a9 100644 --- a/third_party/libassimp/code/ObjFileParser.cpp +++ b/third_party/libassimp/code/Obj/ObjFileParser.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -113,8 +113,7 @@ void ObjFileParser::parseFile( IOStreamBuffer &streamBuffer ) { //const unsigned int updateProgressEveryBytes = 100 * 1024; unsigned int progressCounter = 0; const unsigned int bytesToProcess = static_cast(streamBuffer.size()); - const unsigned int progressTotal = 3 * bytesToProcess; - const unsigned int progressOffset = bytesToProcess; + const unsigned int progressTotal = bytesToProcess; unsigned int processed = 0; size_t lastFilePos( 0 ); @@ -126,10 +125,10 @@ void ObjFileParser::parseFile( IOStreamBuffer &streamBuffer ) { // Handle progress reporting const size_t filePos( streamBuffer.getFilePos() ); if ( lastFilePos < filePos ) { - processed += static_cast(filePos); + processed = static_cast(filePos); lastFilePos = filePos; progressCounter++; - m_progress->UpdateFileRead( progressOffset + processed * 2, progressTotal ); + m_progress->UpdateFileRead( processed, progressTotal ); } // parse line @@ -152,7 +151,8 @@ void ObjFileParser::parseFile( IOStreamBuffer &streamBuffer ) { } else if (*m_DataIt == 't') { // read in texture coordinate ( 2D or 3D ) ++m_DataIt; - getVector( m_pModel->m_TextureCoord ); + size_t dim = getTexCoordVector(m_pModel->m_TextureCoord); + m_pModel->m_TextureCoordDim = std::max(m_pModel->m_TextureCoordDim, (unsigned int)dim); } else if (*m_DataIt == 'n') { // Read in normal vector definition ++m_DataIt; @@ -244,8 +244,8 @@ void ObjFileParser::copyNextWord(char *pBuffer, size_t length) { size_t index = 0; m_DataIt = getNextWord(m_DataIt, m_DataItEnd); if ( *m_DataIt == '\\' ) { - m_DataIt++; - m_DataIt++; + ++m_DataIt; + ++m_DataIt; m_DataIt = getNextWord( m_DataIt, m_DataItEnd ); } while( m_DataIt != m_DataItEnd && !IsSpaceOrNewLine( *m_DataIt ) ) { @@ -272,6 +272,17 @@ static bool isDataDefinitionEnd( const char *tmp ) { return false; } +static bool isNanOrInf(const char * in) { + // Look for "nan" or "inf", case insensitive + if ((in[0] == 'N' || in[0] == 'n') && ASSIMP_strincmp(in, "nan", 3) == 0) { + return true; + } + else if ((in[0] == 'I' || in[0] == 'i') && ASSIMP_strincmp(in, "inf", 3) == 0) { + return true; + } + return false; +} + size_t ObjFileParser::getNumComponentsInDataDefinition() { size_t numComponents( 0 ); const char* tmp( &m_DataIt[0] ); @@ -285,7 +296,7 @@ size_t ObjFileParser::getNumComponentsInDataDefinition() { if ( !SkipSpaces( &tmp ) ) { break; } - const bool isNum( IsNumeric( *tmp ) ); + const bool isNum( IsNumeric( *tmp ) || isNanOrInf(tmp)); SkipToken( tmp ); if ( isNum ) { ++numComponents; @@ -297,7 +308,7 @@ size_t ObjFileParser::getNumComponentsInDataDefinition() { return numComponents; } -void ObjFileParser::getVector( std::vector &point3d_array ) { +size_t ObjFileParser::getTexCoordVector( std::vector &point3d_array ) { size_t numComponents = getNumComponentsInDataDefinition(); ai_real x, y, z; if( 2 == numComponents ) { @@ -319,8 +330,20 @@ void ObjFileParser::getVector( std::vector &point3d_array ) { } else { throw DeadlyImportError( "OBJ: Invalid number of components" ); } + + // Coerce nan and inf to 0 as is the OBJ default value + if (!std::isfinite(x)) + x = 0; + + if (!std::isfinite(y)) + y = 0; + + if (!std::isfinite(z)) + z = 0; + point3d_array.push_back( aiVector3D( x, y, z ) ); m_DataIt = skipLine( m_DataIt, m_DataItEnd, m_uiLine ); + return numComponents; } void ObjFileParser::getVector3( std::vector &point3d_array ) { @@ -428,13 +451,6 @@ void ObjFileParser::getFace( aiPrimitiveType type ) { if (type == aiPrimitiveType_POINT) { ASSIMP_LOG_ERROR("Obj: Separator unexpected in point statement"); } - if (iPos == 0) { - //if there are no texture coordinates in the file, but normals - if (!vt && vn) { - iPos = 1; - iStep++; - } - } iPos++; } else if( IsSpaceOrNewLine( *m_DataIt ) ) { iPos = 0; @@ -451,6 +467,9 @@ void ObjFileParser::getFace( aiPrimitiveType type ) { ++iStep; } + if (iPos == 1 && !vt && vn) + iPos = 2; // skip texture coords for normals if there are no tex coords + if ( iVal > 0 ) { // Store parsed index if ( 0 == iPos ) { diff --git a/third_party/libassimp/code/ObjFileParser.h b/third_party/libassimp/code/Obj/ObjFileParser.h similarity index 98% rename from third_party/libassimp/code/ObjFileParser.h rename to third_party/libassimp/code/Obj/ObjFileParser.h index 7cf06ae05a..7d1b806ce6 100644 --- a/third_party/libassimp/code/ObjFileParser.h +++ b/third_party/libassimp/code/Obj/ObjFileParser.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -96,7 +96,7 @@ protected: /// Get the number of components in a line. size_t getNumComponentsInDataDefinition(); /// Stores the vector - void getVector( std::vector &point3d_array ); + size_t getTexCoordVector( std::vector &point3d_array ); /// Stores the following 3d vector. void getVector3( std::vector &point3d_array ); /// Stores the following homogeneous vector as a 3D vector diff --git a/third_party/libassimp/code/ObjTools.h b/third_party/libassimp/code/Obj/ObjTools.h similarity index 99% rename from third_party/libassimp/code/ObjTools.h rename to third_party/libassimp/code/Obj/ObjTools.h index 842efd749f..3f4c410335 100644 --- a/third_party/libassimp/code/ObjTools.h +++ b/third_party/libassimp/code/Obj/ObjTools.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/OgreBinarySerializer.cpp b/third_party/libassimp/code/Ogre/OgreBinarySerializer.cpp similarity index 99% rename from third_party/libassimp/code/OgreBinarySerializer.cpp rename to third_party/libassimp/code/Ogre/OgreBinarySerializer.cpp index 8948844d03..589e69c7e7 100644 --- a/third_party/libassimp/code/OgreBinarySerializer.cpp +++ b/third_party/libassimp/code/Ogre/OgreBinarySerializer.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -864,6 +864,8 @@ bool OgreBinarySerializer::ImportSkeleton(Assimp::IOSystem *pIOHandler, Mesh *me } MemoryStreamReaderPtr reader = OpenReader(pIOHandler, mesh->skeletonRef); + if (!reader) + return false; Skeleton *skeleton = new Skeleton(); OgreBinarySerializer serializer(reader.get(), OgreBinarySerializer::AM_Skeleton); diff --git a/third_party/libassimp/code/OgreBinarySerializer.h b/third_party/libassimp/code/Ogre/OgreBinarySerializer.h similarity index 99% rename from third_party/libassimp/code/OgreBinarySerializer.h rename to third_party/libassimp/code/Ogre/OgreBinarySerializer.h index a31047c70f..8bab00ce90 100644 --- a/third_party/libassimp/code/OgreBinarySerializer.h +++ b/third_party/libassimp/code/Ogre/OgreBinarySerializer.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/OgreImporter.cpp b/third_party/libassimp/code/Ogre/OgreImporter.cpp similarity index 99% rename from third_party/libassimp/code/OgreImporter.cpp rename to third_party/libassimp/code/Ogre/OgreImporter.cpp index e77654d7b2..c2c328a47a 100644 --- a/third_party/libassimp/code/OgreImporter.cpp +++ b/third_party/libassimp/code/Ogre/OgreImporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/OgreImporter.h b/third_party/libassimp/code/Ogre/OgreImporter.h similarity index 99% rename from third_party/libassimp/code/OgreImporter.h rename to third_party/libassimp/code/Ogre/OgreImporter.h index 8f088a3cca..321d587639 100644 --- a/third_party/libassimp/code/OgreImporter.h +++ b/third_party/libassimp/code/Ogre/OgreImporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/OgreMaterial.cpp b/third_party/libassimp/code/Ogre/OgreMaterial.cpp similarity index 99% rename from third_party/libassimp/code/OgreMaterial.cpp rename to third_party/libassimp/code/Ogre/OgreMaterial.cpp index ceca04da1f..47cb17eb04 100644 --- a/third_party/libassimp/code/OgreMaterial.cpp +++ b/third_party/libassimp/code/Ogre/OgreMaterial.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/OgreParsingUtils.h b/third_party/libassimp/code/Ogre/OgreParsingUtils.h similarity index 99% rename from third_party/libassimp/code/OgreParsingUtils.h rename to third_party/libassimp/code/Ogre/OgreParsingUtils.h index c6b6e0caf5..8786521e43 100644 --- a/third_party/libassimp/code/OgreParsingUtils.h +++ b/third_party/libassimp/code/Ogre/OgreParsingUtils.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/OgreStructs.cpp b/third_party/libassimp/code/Ogre/OgreStructs.cpp similarity index 99% rename from third_party/libassimp/code/OgreStructs.cpp rename to third_party/libassimp/code/Ogre/OgreStructs.cpp index b2ad8e0892..7962202c15 100644 --- a/third_party/libassimp/code/OgreStructs.cpp +++ b/third_party/libassimp/code/Ogre/OgreStructs.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/OgreStructs.h b/third_party/libassimp/code/Ogre/OgreStructs.h similarity index 99% rename from third_party/libassimp/code/OgreStructs.h rename to third_party/libassimp/code/Ogre/OgreStructs.h index dfe0346dc5..6ea211e103 100644 --- a/third_party/libassimp/code/OgreStructs.h +++ b/third_party/libassimp/code/Ogre/OgreStructs.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/OgreXmlSerializer.cpp b/third_party/libassimp/code/Ogre/OgreXmlSerializer.cpp similarity index 99% rename from third_party/libassimp/code/OgreXmlSerializer.cpp rename to third_party/libassimp/code/Ogre/OgreXmlSerializer.cpp index 5805a528d3..19fd3ad612 100644 --- a/third_party/libassimp/code/OgreXmlSerializer.cpp +++ b/third_party/libassimp/code/Ogre/OgreXmlSerializer.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/OgreXmlSerializer.h b/third_party/libassimp/code/Ogre/OgreXmlSerializer.h similarity index 99% rename from third_party/libassimp/code/OgreXmlSerializer.h rename to third_party/libassimp/code/Ogre/OgreXmlSerializer.h index c0f09096c5..7e5e83fec9 100644 --- a/third_party/libassimp/code/OgreXmlSerializer.h +++ b/third_party/libassimp/code/Ogre/OgreXmlSerializer.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/OpenGEXExporter.cpp b/third_party/libassimp/code/OpenGEX/OpenGEXExporter.cpp similarity index 98% rename from third_party/libassimp/code/OpenGEXExporter.cpp rename to third_party/libassimp/code/OpenGEX/OpenGEXExporter.cpp index ea2f64e8f0..635174185f 100644 --- a/third_party/libassimp/code/OpenGEXExporter.cpp +++ b/third_party/libassimp/code/OpenGEX/OpenGEXExporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/OpenGEXExporter.h b/third_party/libassimp/code/OpenGEX/OpenGEXExporter.h similarity index 98% rename from third_party/libassimp/code/OpenGEXExporter.h rename to third_party/libassimp/code/OpenGEX/OpenGEXExporter.h index 76d2418a47..b9b54c208e 100644 --- a/third_party/libassimp/code/OpenGEXExporter.h +++ b/third_party/libassimp/code/OpenGEX/OpenGEXExporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/OpenGEXImporter.cpp b/third_party/libassimp/code/OpenGEX/OpenGEXImporter.cpp similarity index 99% rename from third_party/libassimp/code/OpenGEXImporter.cpp rename to third_party/libassimp/code/OpenGEX/OpenGEXImporter.cpp index 2de0aabc0a..07d3efd5e1 100644 --- a/third_party/libassimp/code/OpenGEXImporter.cpp +++ b/third_party/libassimp/code/OpenGEX/OpenGEXImporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -41,10 +41,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ASSIMP_BUILD_NO_OPENGEX_IMPORTER -#include "OpenGEXImporter.h" +#include "OpenGEX/OpenGEXImporter.h" +#include "PostProcessing/MakeVerboseFormat.h" + #include #include -#include "MakeVerboseFormat.h" #include #include @@ -212,7 +213,11 @@ static void propId2StdString( Property *prop, std::string &name, std::string &ke } if ( nullptr != prop->m_key ) { +#ifdef ASSIMP_USE_HUNTER + name = prop->m_key->m_text.m_buffer; +#else name = prop->m_key->m_buffer; +#endif if ( Value::ddl_string == prop->m_value->m_type ) { key = prop->m_value->getString(); } @@ -497,7 +502,11 @@ static void getRefNames( DDLNode *node, std::vector &names ) { for( size_t i = 0; i < ref->m_numRefs; i++ ) { Name *currentName( ref->m_referencedName[ i ] ); if( nullptr != currentName && nullptr != currentName->m_id ) { +#ifdef ASSIMP_USE_HUNTER + const std::string name( currentName->m_id->m_text.m_buffer ); +#else const std::string name( currentName->m_id->m_buffer ); +#endif if( !name.empty() ) { names.push_back( name ); } @@ -1038,7 +1047,11 @@ void OpenGEXImporter::handleColorNode( ODDLParser::DDLNode *node, aiScene * /*pS col.g = col4.g; col.b = col4.b; } +#ifdef ASSIMP_USE_HUNTER + const ColorType colType( getColorType( &prop->m_key->m_text ) ); +#else const ColorType colType( getColorType( prop->m_key ) ); +#endif if( DiffuseColor == colType ) { m_currentMaterial->AddProperty( &col, 1, AI_MATKEY_COLOR_DIFFUSE ); } else if( SpecularColor == colType ) { diff --git a/third_party/libassimp/code/OpenGEXImporter.h b/third_party/libassimp/code/OpenGEX/OpenGEXImporter.h similarity index 99% rename from third_party/libassimp/code/OpenGEXImporter.h rename to third_party/libassimp/code/OpenGEX/OpenGEXImporter.h index 8e86a4aa8a..22b5cabefb 100644 --- a/third_party/libassimp/code/OpenGEXImporter.h +++ b/third_party/libassimp/code/OpenGEX/OpenGEXImporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/OpenGEXStructs.h b/third_party/libassimp/code/OpenGEX/OpenGEXStructs.h similarity index 99% rename from third_party/libassimp/code/OpenGEXStructs.h rename to third_party/libassimp/code/OpenGEX/OpenGEXStructs.h index 6cd7488e92..2c83e86609 100644 --- a/third_party/libassimp/code/OpenGEXStructs.h +++ b/third_party/libassimp/code/OpenGEX/OpenGEXStructs.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/PlyExporter.cpp b/third_party/libassimp/code/Ply/PlyExporter.cpp similarity index 99% rename from third_party/libassimp/code/PlyExporter.cpp rename to third_party/libassimp/code/Ply/PlyExporter.cpp index 31c64a4d14..5e21a88acb 100644 --- a/third_party/libassimp/code/PlyExporter.cpp +++ b/third_party/libassimp/code/Ply/PlyExporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -111,7 +111,7 @@ PlyExporter::PlyExporter(const char* _filename, const aiScene* pScene, bool bina // make sure that all formatting happens using the standard, C locale and not the user's current locale const std::locale& l = std::locale("C"); mOutput.imbue(l); - mOutput.precision(16); + mOutput.precision(ASSIMP_AI_REAL_TEXT_PRECISION); unsigned int faces = 0u, vertices = 0u, components = 0u; for (unsigned int i = 0; i < pScene->mNumMeshes; ++i) { diff --git a/third_party/libassimp/code/PlyExporter.h b/third_party/libassimp/code/Ply/PlyExporter.h similarity index 98% rename from third_party/libassimp/code/PlyExporter.h rename to third_party/libassimp/code/Ply/PlyExporter.h index 060aa7ceb2..b82498cbda 100644 --- a/third_party/libassimp/code/PlyExporter.h +++ b/third_party/libassimp/code/Ply/PlyExporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/PlyLoader.cpp b/third_party/libassimp/code/Ply/PlyLoader.cpp similarity index 99% rename from third_party/libassimp/code/PlyLoader.cpp rename to third_party/libassimp/code/Ply/PlyLoader.cpp index 7e55e6c3eb..3924305cb2 100644 --- a/third_party/libassimp/code/PlyLoader.cpp +++ b/third_party/libassimp/code/Ply/PlyLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/PlyLoader.h b/third_party/libassimp/code/Ply/PlyLoader.h similarity index 99% rename from third_party/libassimp/code/PlyLoader.h rename to third_party/libassimp/code/Ply/PlyLoader.h index 9199e17d72..201c463b22 100644 --- a/third_party/libassimp/code/PlyLoader.h +++ b/third_party/libassimp/code/Ply/PlyLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/PlyParser.cpp b/third_party/libassimp/code/Ply/PlyParser.cpp similarity index 99% rename from third_party/libassimp/code/PlyParser.cpp rename to third_party/libassimp/code/Ply/PlyParser.cpp index b51b6ac71f..2a6f00ad65 100644 --- a/third_party/libassimp/code/PlyParser.cpp +++ b/third_party/libassimp/code/Ply/PlyParser.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/PlyParser.h b/third_party/libassimp/code/Ply/PlyParser.h similarity index 99% rename from third_party/libassimp/code/PlyParser.h rename to third_party/libassimp/code/Ply/PlyParser.h index b544c3b047..a11b411d18 100644 --- a/third_party/libassimp/code/PlyParser.h +++ b/third_party/libassimp/code/Ply/PlyParser.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/CalcTangentsProcess.cpp b/third_party/libassimp/code/PostProcessing/CalcTangentsProcess.cpp similarity index 98% rename from third_party/libassimp/code/CalcTangentsProcess.cpp rename to third_party/libassimp/code/PostProcessing/CalcTangentsProcess.cpp index a25fbb27c8..cc4935638c 100644 --- a/third_party/libassimp/code/CalcTangentsProcess.cpp +++ b/third_party/libassimp/code/PostProcessing/CalcTangentsProcess.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -212,7 +212,7 @@ bool CalcTangentsProcess::ProcessMesh( aiMesh* pMesh, unsigned int meshIndex) // project tangent and bitangent into the plane formed by the vertex' normal aiVector3D localTangent = tangent - meshNorm[p] * (tangent * meshNorm[p]); aiVector3D localBitangent = bitangent - meshNorm[p] * (bitangent * meshNorm[p]); - localTangent.Normalize(); localBitangent.Normalize(); + localTangent.NormalizeSafe(); localBitangent.NormalizeSafe(); // reconstruct tangent/bitangent according to normal and bitangent/tangent when it's infinite or NaN. bool invalid_tangent = is_special_float(localTangent.x) || is_special_float(localTangent.y) || is_special_float(localTangent.z); @@ -220,10 +220,10 @@ bool CalcTangentsProcess::ProcessMesh( aiMesh* pMesh, unsigned int meshIndex) if (invalid_tangent != invalid_bitangent) { if (invalid_tangent) { localTangent = meshNorm[p] ^ localBitangent; - localTangent.Normalize(); + localTangent.NormalizeSafe(); } else { localBitangent = localTangent ^ meshNorm[p]; - localBitangent.Normalize(); + localBitangent.NormalizeSafe(); } } diff --git a/third_party/libassimp/code/CalcTangentsProcess.h b/third_party/libassimp/code/PostProcessing/CalcTangentsProcess.h similarity index 97% rename from third_party/libassimp/code/CalcTangentsProcess.h rename to third_party/libassimp/code/PostProcessing/CalcTangentsProcess.h index 4cac2ed9ff..3568a624f8 100644 --- a/third_party/libassimp/code/CalcTangentsProcess.h +++ b/third_party/libassimp/code/PostProcessing/CalcTangentsProcess.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -42,11 +42,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** @file Defines a post processing step to calculate tangents and - bitangents on all imported meshes.*/ + bi-tangents on all imported meshes.*/ #ifndef AI_CALCTANGENTSPROCESS_H_INC #define AI_CALCTANGENTSPROCESS_H_INC -#include "BaseProcess.h" +#include "Common/BaseProcess.h" struct aiMesh; diff --git a/third_party/libassimp/code/ComputeUVMappingProcess.cpp b/third_party/libassimp/code/PostProcessing/ComputeUVMappingProcess.cpp similarity index 99% rename from third_party/libassimp/code/ComputeUVMappingProcess.cpp rename to third_party/libassimp/code/PostProcessing/ComputeUVMappingProcess.cpp index 3b0577b2d6..df4d44337d 100644 --- a/third_party/libassimp/code/ComputeUVMappingProcess.cpp +++ b/third_party/libassimp/code/PostProcessing/ComputeUVMappingProcess.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -354,12 +354,12 @@ void ComputeUVMappingProcess::ComputePlaneMapping(aiMesh* mesh,const aiVector3D& } else if (axis * base_axis_z >= angle_epsilon) { FindMeshCenter(mesh, center, min, max); - diffu = max.y - min.y; - diffv = max.z - min.z; + diffu = max.x - min.x; + diffv = max.y - min.y; for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { const aiVector3D& pos = mesh->mVertices[pnt]; - out[pnt].Set((pos.y - min.y) / diffu,(pos.x - min.x) / diffv,0.0); + out[pnt].Set((pos.x - min.x) / diffu,(pos.y - min.y) / diffv,0.0); } } // slower code path in case the mapping axis is not one of the coordinate system axes diff --git a/third_party/libassimp/code/ComputeUVMappingProcess.h b/third_party/libassimp/code/PostProcessing/ComputeUVMappingProcess.h similarity index 98% rename from third_party/libassimp/code/ComputeUVMappingProcess.h rename to third_party/libassimp/code/PostProcessing/ComputeUVMappingProcess.h index 41e25f99fa..a6d36e06ea 100644 --- a/third_party/libassimp/code/ComputeUVMappingProcess.h +++ b/third_party/libassimp/code/PostProcessing/ComputeUVMappingProcess.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -45,7 +45,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_COMPUTEUVMAPPING_H_INC #define AI_COMPUTEUVMAPPING_H_INC -#include "BaseProcess.h" +#include "Common/BaseProcess.h" + #include #include #include diff --git a/third_party/libassimp/code/ConvertToLHProcess.cpp b/third_party/libassimp/code/PostProcessing/ConvertToLHProcess.cpp similarity index 83% rename from third_party/libassimp/code/ConvertToLHProcess.cpp rename to third_party/libassimp/code/PostProcessing/ConvertToLHProcess.cpp index 9cb45cc698..b7cd4f0bc6 100644 --- a/third_party/libassimp/code/ConvertToLHProcess.cpp +++ b/third_party/libassimp/code/PostProcessing/ConvertToLHProcess.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -166,8 +166,9 @@ void MakeLeftHandedProcess::ProcessMesh( aiMesh* pMesh) { for( size_t a = 0; a < pMesh->mNumVertices; ++a) { pMesh->mVertices[a].z *= -1.0f; - if( pMesh->HasNormals()) + if (pMesh->HasNormals()) { pMesh->mNormals[a].z *= -1.0f; + } if( pMesh->HasTangentsAndBitangents()) { pMesh->mTangents[a].z *= -1.0f; @@ -175,6 +176,23 @@ void MakeLeftHandedProcess::ProcessMesh( aiMesh* pMesh) { } } + // mirror anim meshes positions, normals and stuff along the Z axis + for (size_t m = 0; m < pMesh->mNumAnimMeshes; ++m) + { + for (size_t a = 0; a < pMesh->mAnimMeshes[m]->mNumVertices; ++a) + { + pMesh->mAnimMeshes[m]->mVertices[a].z *= -1.0f; + if (pMesh->mAnimMeshes[m]->HasNormals()) { + pMesh->mAnimMeshes[m]->mNormals[a].z *= -1.0f; + } + if (pMesh->mAnimMeshes[m]->HasTangentsAndBitangents()) + { + pMesh->mAnimMeshes[m]->mTangents[a].z *= -1.0f; + pMesh->mAnimMeshes[m]->mBitangents[a].z *= -1.0f; + } + } + } + // mirror offset matrices of all bones for( size_t a = 0; a < pMesh->mNumBones; ++a) { @@ -346,8 +364,50 @@ void FlipWindingOrderProcess::ProcessMesh( aiMesh* pMesh) for( unsigned int a = 0; a < pMesh->mNumFaces; a++) { aiFace& face = pMesh->mFaces[a]; - for( unsigned int b = 0; b < face.mNumIndices / 2; b++) - std::swap( face.mIndices[b], face.mIndices[ face.mNumIndices - 1 - b]); + for (unsigned int b = 0; b < face.mNumIndices / 2; b++) { + std::swap(face.mIndices[b], face.mIndices[face.mNumIndices - 1 - b]); + } + } + + // invert the order of all components in this mesh anim meshes + for (unsigned int m = 0; m < pMesh->mNumAnimMeshes; m++) { + aiAnimMesh* animMesh = pMesh->mAnimMeshes[m]; + unsigned int numVertices = animMesh->mNumVertices; + if (animMesh->HasPositions()) { + for (unsigned int a = 0; a < numVertices; a++) + { + std::swap(animMesh->mVertices[a], animMesh->mVertices[numVertices - 1 - a]); + } + } + if (animMesh->HasNormals()) { + for (unsigned int a = 0; a < numVertices; a++) + { + std::swap(animMesh->mNormals[a], animMesh->mNormals[numVertices - 1 - a]); + } + } + for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; i++) { + if (animMesh->HasTextureCoords(i)) { + for (unsigned int a = 0; a < numVertices; a++) + { + std::swap(animMesh->mTextureCoords[i][a], animMesh->mTextureCoords[i][numVertices - 1 - a]); + } + } + } + if (animMesh->HasTangentsAndBitangents()) { + for (unsigned int a = 0; a < numVertices; a++) + { + std::swap(animMesh->mTangents[a], animMesh->mTangents[numVertices - 1 - a]); + std::swap(animMesh->mBitangents[a], animMesh->mBitangents[numVertices - 1 - a]); + } + } + for (unsigned int v = 0; v < AI_MAX_NUMBER_OF_COLOR_SETS; v++) { + if (animMesh->HasVertexColors(v)) { + for (unsigned int a = 0; a < numVertices; a++) + { + std::swap(animMesh->mColors[v][a], animMesh->mColors[v][numVertices - 1 - a]); + } + } + } } } diff --git a/third_party/libassimp/code/ConvertToLHProcess.h b/third_party/libassimp/code/PostProcessing/ConvertToLHProcess.h similarity index 98% rename from third_party/libassimp/code/ConvertToLHProcess.h rename to third_party/libassimp/code/PostProcessing/ConvertToLHProcess.h index f219d6ca25..f32b91fc39 100644 --- a/third_party/libassimp/code/ConvertToLHProcess.h +++ b/third_party/libassimp/code/PostProcessing/ConvertToLHProcess.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -52,7 +52,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define AI_CONVERTTOLHPROCESS_H_INC #include -#include "BaseProcess.h" + +#include "Common/BaseProcess.h" struct aiMesh; struct aiNodeAnim; diff --git a/third_party/libassimp/code/DeboneProcess.cpp b/third_party/libassimp/code/PostProcessing/DeboneProcess.cpp similarity index 99% rename from third_party/libassimp/code/DeboneProcess.cpp rename to third_party/libassimp/code/PostProcessing/DeboneProcess.cpp index bc6afa36ec..83b8336bc9 100644 --- a/third_party/libassimp/code/DeboneProcess.cpp +++ b/third_party/libassimp/code/PostProcessing/DeboneProcess.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/DeboneProcess.h b/third_party/libassimp/code/PostProcessing/DeboneProcess.h similarity index 96% rename from third_party/libassimp/code/DeboneProcess.h rename to third_party/libassimp/code/PostProcessing/DeboneProcess.h index 3da8613625..8b64c2acc6 100644 --- a/third_party/libassimp/code/DeboneProcess.h +++ b/third_party/libassimp/code/PostProcessing/DeboneProcess.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -44,17 +44,18 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_DEBONEPROCESS_H_INC #define AI_DEBONEPROCESS_H_INC -#include -#include -#include "BaseProcess.h" +#include "Common/BaseProcess.h" #include #include +#include +#include + +#// Forward declarations class DeboneTest; -namespace Assimp -{ +namespace Assimp { #if (!defined AI_DEBONE_THRESHOLD) # define AI_DEBONE_THRESHOLD 1.0f @@ -66,14 +67,11 @@ namespace Assimp * the bone are split from the mesh. The split off (new) mesh is boneless. At any * point in time, bones without affect upon a given mesh are to be removed. */ -class DeboneProcess : public BaseProcess -{ +class DeboneProcess : public BaseProcess { public: - DeboneProcess(); ~DeboneProcess(); -public: // ------------------------------------------------------------------- /** Returns whether the processing step is present in the given flag. * @param pFlags The processing flags the importer was called with. @@ -91,7 +89,6 @@ public: void SetupProperties(const Importer* pImp); protected: - // ------------------------------------------------------------------- /** Executes the post processing step on the given imported data. * At the moment a process is not supposed to fail. diff --git a/third_party/libassimp/code/DropFaceNormalsProcess.cpp b/third_party/libassimp/code/PostProcessing/DropFaceNormalsProcess.cpp similarity index 99% rename from third_party/libassimp/code/DropFaceNormalsProcess.cpp rename to third_party/libassimp/code/PostProcessing/DropFaceNormalsProcess.cpp index 57e8b972b9..b11615bb82 100644 --- a/third_party/libassimp/code/DropFaceNormalsProcess.cpp +++ b/third_party/libassimp/code/PostProcessing/DropFaceNormalsProcess.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/DropFaceNormalsProcess.h b/third_party/libassimp/code/PostProcessing/DropFaceNormalsProcess.h similarity index 96% rename from third_party/libassimp/code/DropFaceNormalsProcess.h rename to third_party/libassimp/code/PostProcessing/DropFaceNormalsProcess.h index 6dbfe03976..c710c5a5ee 100644 --- a/third_party/libassimp/code/DropFaceNormalsProcess.h +++ b/third_party/libassimp/code/PostProcessing/DropFaceNormalsProcess.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -44,23 +44,20 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_DROPFACENORMALPROCESS_H_INC #define AI_DROPFACENORMALPROCESS_H_INC -#include "BaseProcess.h" +#include "Common/BaseProcess.h" + #include -namespace Assimp -{ +namespace Assimp { // --------------------------------------------------------------------------- /** The DropFaceNormalsProcess computes face normals for all faces of all meshes */ -class ASSIMP_API_WINONLY DropFaceNormalsProcess : public BaseProcess -{ +class ASSIMP_API_WINONLY DropFaceNormalsProcess : public BaseProcess { public: - DropFaceNormalsProcess(); ~DropFaceNormalsProcess(); -public: // ------------------------------------------------------------------- /** Returns whether the processing step is present in the given flag field. * @param pFlags The processing flags the importer was called with. A bitwise diff --git a/third_party/libassimp/code/EmbedTexturesProcess.cpp b/third_party/libassimp/code/PostProcessing/EmbedTexturesProcess.cpp similarity index 91% rename from third_party/libassimp/code/EmbedTexturesProcess.cpp rename to third_party/libassimp/code/PostProcessing/EmbedTexturesProcess.cpp index ebe7a08970..739382a057 100644 --- a/third_party/libassimp/code/EmbedTexturesProcess.cpp +++ b/third_party/libassimp/code/PostProcessing/EmbedTexturesProcess.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -124,22 +124,28 @@ bool EmbedTexturesProcess::addTexture(aiScene* pScene, std::string path) const { file.read(reinterpret_cast(imageContent), imageSize); // Enlarging the textures table - auto textureId = pScene->mNumTextures++; + unsigned int textureId = pScene->mNumTextures++; auto oldTextures = pScene->mTextures; pScene->mTextures = new aiTexture*[pScene->mNumTextures]; - memmove(pScene->mTextures, oldTextures, sizeof(aiTexture*) * (pScene->mNumTextures - 1u)); + ::memmove(pScene->mTextures, oldTextures, sizeof(aiTexture*) * (pScene->mNumTextures - 1u)); // Add the new texture - auto pTexture = new aiTexture(); + auto pTexture = new aiTexture; pTexture->mHeight = 0; // Means that this is still compressed pTexture->mWidth = static_cast(imageSize); pTexture->pcData = imageContent; auto extension = path.substr(path.find_last_of('.') + 1u); std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower); - if (extension == "jpeg") extension = "jpg"; - strcpy(pTexture->achFormatHint, extension.c_str()); + if (extension == "jpeg") { + extension = "jpg"; + } + size_t len = extension.size(); + if (len > HINTMAXTEXTURELEN -1 ) { + len = HINTMAXTEXTURELEN - 1; + } + ::strncpy(pTexture->achFormatHint, extension.c_str(), len); pScene->mTextures[textureId] = pTexture; return true; diff --git a/third_party/libassimp/code/EmbedTexturesProcess.h b/third_party/libassimp/code/PostProcessing/EmbedTexturesProcess.h similarity index 97% rename from third_party/libassimp/code/EmbedTexturesProcess.h rename to third_party/libassimp/code/PostProcessing/EmbedTexturesProcess.h index ce9821652f..3c4b2eab4e 100644 --- a/third_party/libassimp/code/EmbedTexturesProcess.h +++ b/third_party/libassimp/code/PostProcessing/EmbedTexturesProcess.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -42,7 +42,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma once -#include "BaseProcess.h" +#include "Common/BaseProcess.h" #include diff --git a/third_party/libassimp/code/FindDegenerates.cpp b/third_party/libassimp/code/PostProcessing/FindDegenerates.cpp similarity index 99% rename from third_party/libassimp/code/FindDegenerates.cpp rename to third_party/libassimp/code/PostProcessing/FindDegenerates.cpp index c0c0de08bc..50fac46dba 100644 --- a/third_party/libassimp/code/FindDegenerates.cpp +++ b/third_party/libassimp/code/PostProcessing/FindDegenerates.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -228,6 +228,7 @@ bool FindDegeneratesProcess::ExecuteOnMesh( aiMesh* mesh) { if ( area < 1e-6 ) { if ( mConfigRemoveDegenerates ) { remove_me[ a ] = true; + ++deg; goto evil_jump_outside; } diff --git a/third_party/libassimp/code/FindDegenerates.h b/third_party/libassimp/code/PostProcessing/FindDegenerates.h similarity index 98% rename from third_party/libassimp/code/FindDegenerates.h rename to third_party/libassimp/code/PostProcessing/FindDegenerates.h index c234c57f59..7a15e77cf1 100644 --- a/third_party/libassimp/code/FindDegenerates.h +++ b/third_party/libassimp/code/PostProcessing/FindDegenerates.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -45,7 +45,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_FINDDEGENERATESPROCESS_H_INC #define AI_FINDDEGENERATESPROCESS_H_INC -#include "BaseProcess.h" +#include "Common/BaseProcess.h" + #include class FindDegeneratesProcessTest; diff --git a/third_party/libassimp/code/FindInstancesProcess.cpp b/third_party/libassimp/code/PostProcessing/FindInstancesProcess.cpp similarity index 92% rename from third_party/libassimp/code/FindInstancesProcess.cpp rename to third_party/libassimp/code/PostProcessing/FindInstancesProcess.cpp index 25dcc51e83..64907458a1 100644 --- a/third_party/libassimp/code/FindInstancesProcess.cpp +++ b/third_party/libassimp/code/PostProcessing/FindInstancesProcess.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -137,6 +137,11 @@ void FindInstancesProcess::Execute( aiScene* pScene) aiMesh* inst = pScene->mMeshes[i]; hashes[i] = GetMeshHash(inst); + // Find an appropriate epsilon + // to compare position differences against + float epsilon = ComputePositionEpsilon(inst); + epsilon *= epsilon; + for (int a = i-1; a >= 0; --a) { if (hashes[i] == hashes[a]) { @@ -154,12 +159,7 @@ void FindInstancesProcess::Execute( aiScene* pScene) orig->mPrimitiveTypes != inst->mPrimitiveTypes) continue; - // up to now the meshes are equal. find an appropriate - // epsilon to compare position differences against - float epsilon = ComputePositionEpsilon(inst); - epsilon *= epsilon; - - // now compare vertex positions, normals, + // up to now the meshes are equal. Now compare vertex positions, normals, // tangents and bitangents using this epsilon. if (orig->HasPositions()) { if(!CompareArrays(orig->mVertices,inst->mVertices,orig->mNumVertices,epsilon)) @@ -178,30 +178,30 @@ void FindInstancesProcess::Execute( aiScene* pScene) // use a constant epsilon for colors and UV coordinates static const float uvEpsilon = 10e-4f; { - unsigned int i, end = orig->GetNumUVChannels(); - for(i = 0; i < end; ++i) { - if (!orig->mTextureCoords[i]) { + unsigned int j, end = orig->GetNumUVChannels(); + for(j = 0; j < end; ++j) { + if (!orig->mTextureCoords[j]) { continue; } - if(!CompareArrays(orig->mTextureCoords[i],inst->mTextureCoords[i],orig->mNumVertices,uvEpsilon)) { + if(!CompareArrays(orig->mTextureCoords[j],inst->mTextureCoords[j],orig->mNumVertices,uvEpsilon)) { break; } } - if (i != end) { + if (j != end) { continue; } } { - unsigned int i, end = orig->GetNumColorChannels(); - for(i = 0; i < end; ++i) { - if (!orig->mColors[i]) { + unsigned int j, end = orig->GetNumColorChannels(); + for(j = 0; j < end; ++j) { + if (!orig->mColors[j]) { continue; } - if(!CompareArrays(orig->mColors[i],inst->mColors[i],orig->mNumVertices,uvEpsilon)) { + if(!CompareArrays(orig->mColors[j],inst->mColors[j],orig->mNumVertices,uvEpsilon)) { break; } } - if (i != end) { + if (j != end) { continue; } } diff --git a/third_party/libassimp/code/FindInstancesProcess.h b/third_party/libassimp/code/PostProcessing/FindInstancesProcess.h similarity index 97% rename from third_party/libassimp/code/FindInstancesProcess.h rename to third_party/libassimp/code/PostProcessing/FindInstancesProcess.h index fb2ac6eb62..64b838d7cc 100644 --- a/third_party/libassimp/code/FindInstancesProcess.h +++ b/third_party/libassimp/code/PostProcessing/FindInstancesProcess.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -46,8 +46,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_FINDINSTANCES_H_INC #define AI_FINDINSTANCES_H_INC -#include "BaseProcess.h" -#include "ProcessHelper.h" +#include "Common/BaseProcess.h" +#include "PostProcessing/ProcessHelper.h" class FindInstancesProcessTest; namespace Assimp { diff --git a/third_party/libassimp/code/FindInvalidDataProcess.cpp b/third_party/libassimp/code/PostProcessing/FindInvalidDataProcess.cpp similarity index 85% rename from third_party/libassimp/code/FindInvalidDataProcess.cpp rename to third_party/libassimp/code/PostProcessing/FindInvalidDataProcess.cpp index b1a296a541..433f042448 100644 --- a/third_party/libassimp/code/FindInvalidDataProcess.cpp +++ b/third_party/libassimp/code/PostProcessing/FindInvalidDataProcess.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -51,6 +51,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // internal headers #include "FindInvalidDataProcess.h" #include "ProcessHelper.h" + #include #include #include @@ -60,37 +61,34 @@ using namespace Assimp; // ------------------------------------------------------------------------------------------------ // Constructor to be privately used by Importer FindInvalidDataProcess::FindInvalidDataProcess() - : configEpsilon(0.0) -{ +: configEpsilon(0.0) +, mIgnoreTexCoods( false ){ // nothing to do here } // ------------------------------------------------------------------------------------------------ // Destructor, private as well -FindInvalidDataProcess::~FindInvalidDataProcess() -{ +FindInvalidDataProcess::~FindInvalidDataProcess() { // nothing to do here } // ------------------------------------------------------------------------------------------------ // Returns whether the processing step is present in the given flag field. -bool FindInvalidDataProcess::IsActive( unsigned int pFlags) const -{ +bool FindInvalidDataProcess::IsActive( unsigned int pFlags) const { return 0 != (pFlags & aiProcess_FindInvalidData); } // ------------------------------------------------------------------------------------------------ // Setup import configuration -void FindInvalidDataProcess::SetupProperties(const Importer* pImp) -{ +void FindInvalidDataProcess::SetupProperties(const Importer* pImp) { // Get the current value of AI_CONFIG_PP_FID_ANIM_ACCURACY configEpsilon = (0 != pImp->GetPropertyFloat(AI_CONFIG_PP_FID_ANIM_ACCURACY,0.f)); + mIgnoreTexCoods = pImp->GetPropertyBool(AI_CONFIG_PP_FID_IGNORE_TEXTURECOORDS, false); } // ------------------------------------------------------------------------------------------------ // Update mesh references in the node graph -void UpdateMeshReferences(aiNode* node, const std::vector& meshMapping) -{ +void UpdateMeshReferences(aiNode* node, const std::vector& meshMapping) { if (node->mNumMeshes) { unsigned int out = 0; for (unsigned int a = 0; a < node->mNumMeshes;++a) { @@ -116,8 +114,7 @@ void UpdateMeshReferences(aiNode* node, const std::vector& meshMap // ------------------------------------------------------------------------------------------------ // Executes the post processing step on the given imported data. -void FindInvalidDataProcess::Execute( aiScene* pScene) -{ +void FindInvalidDataProcess::Execute( aiScene* pScene) { ASSIMP_LOG_DEBUG("FindInvalidDataProcess begin"); bool out = false; @@ -171,17 +168,18 @@ void FindInvalidDataProcess::Execute( aiScene* pScene) // ------------------------------------------------------------------------------------------------ template -inline const char* ValidateArrayContents(const T* /*arr*/, unsigned int /*size*/, - const std::vector& /*dirtyMask*/, bool /*mayBeIdentical = false*/, bool /*mayBeZero = true*/) +inline +const char* ValidateArrayContents(const T* /*arr*/, unsigned int /*size*/, + const std::vector& /*dirtyMask*/, bool /*mayBeIdentical = false*/, bool /*mayBeZero = true*/) { - return NULL; + return nullptr; } // ------------------------------------------------------------------------------------------------ template <> -inline const char* ValidateArrayContents(const aiVector3D* arr, unsigned int size, - const std::vector& dirtyMask, bool mayBeIdentical , bool mayBeZero ) -{ +inline +const char* ValidateArrayContents(const aiVector3D* arr, unsigned int size, + const std::vector& dirtyMask, bool mayBeIdentical , bool mayBeZero ) { bool b = false; unsigned int cnt = 0; for (unsigned int i = 0; i < size;++i) { @@ -203,14 +201,14 @@ inline const char* ValidateArrayContents(const aiVector3D* arr, unsi if (cnt > 1 && !b && !mayBeIdentical) { return "All vectors are identical"; } - return NULL; + return nullptr; } // ------------------------------------------------------------------------------------------------ template -inline bool ProcessArray(T*& in, unsigned int num,const char* name, - const std::vector& dirtyMask, bool mayBeIdentical = false, bool mayBeZero = true) -{ +inline +bool ProcessArray(T*& in, unsigned int num,const char* name, + const std::vector& dirtyMask, bool mayBeIdentical = false, bool mayBeZero = true) { const char* err = ValidateArrayContents(in,num,dirtyMask,mayBeIdentical,mayBeZero); if (err) { ASSIMP_LOG_ERROR_F( "FindInvalidDataProcess fails on mesh ", name, ": ", err); @@ -251,23 +249,20 @@ bool EpsilonCompare(const aiQuatKey& n, const aiQuatKey& s, ai_real e // ------------------------------------------------------------------------------------------------ template -inline bool AllIdentical(T* in, unsigned int num, ai_real epsilon) -{ +inline +bool AllIdentical(T* in, unsigned int num, ai_real epsilon) { if (num <= 1) { return true; } - if (epsilon > 0.f) { + if (fabs(epsilon) > 0.f) { for (unsigned int i = 0; i < num-1;++i) { - if (!EpsilonCompare(in[i],in[i+1],epsilon)) { return false; } } - } - else { + } else { for (unsigned int i = 0; i < num-1;++i) { - if (in[i] != in[i+1]) { return false; } @@ -278,27 +273,26 @@ inline bool AllIdentical(T* in, unsigned int num, ai_real epsilon) // ------------------------------------------------------------------------------------------------ // Search an animation for invalid content -void FindInvalidDataProcess::ProcessAnimation (aiAnimation* anim) -{ +void FindInvalidDataProcess::ProcessAnimation (aiAnimation* anim) { // Process all animation channels - for (unsigned int a = 0; a < anim->mNumChannels;++a) { + for ( unsigned int a = 0; a < anim->mNumChannels; ++a ) { ProcessAnimationChannel( anim->mChannels[a]); } } // ------------------------------------------------------------------------------------------------ -void FindInvalidDataProcess::ProcessAnimationChannel (aiNodeAnim* anim) -{ - int i = 0; - - // ScenePreprocessor's work ... - ai_assert((0 != anim->mPositionKeys && 0 != anim->mRotationKeys && 0 != anim->mScalingKeys)); +void FindInvalidDataProcess::ProcessAnimationChannel (aiNodeAnim* anim) { + ai_assert( nullptr != anim ); + if (anim->mNumPositionKeys == 0 && anim->mNumRotationKeys == 0 && anim->mNumScalingKeys == 0) { + ai_assert_entry(); + return; + } // Check whether all values in a tracks are identical - in this case // we can remove al keys except one. // POSITIONS - if (anim->mNumPositionKeys > 1 && AllIdentical(anim->mPositionKeys,anim->mNumPositionKeys,configEpsilon)) - { + int i = 0; + if (anim->mNumPositionKeys > 1 && AllIdentical(anim->mPositionKeys,anim->mNumPositionKeys,configEpsilon)) { aiVectorKey v = anim->mPositionKeys[0]; // Reallocate ... we need just ONE element, it makes no sense to reuse the array @@ -309,8 +303,7 @@ void FindInvalidDataProcess::ProcessAnimationChannel (aiNodeAnim* anim) } // ROTATIONS - if (anim->mNumRotationKeys > 1 && AllIdentical(anim->mRotationKeys,anim->mNumRotationKeys,configEpsilon)) - { + if (anim->mNumRotationKeys > 1 && AllIdentical(anim->mRotationKeys,anim->mNumRotationKeys,configEpsilon)) { aiQuatKey v = anim->mRotationKeys[0]; // Reallocate ... we need just ONE element, it makes no sense to reuse the array @@ -321,8 +314,7 @@ void FindInvalidDataProcess::ProcessAnimationChannel (aiNodeAnim* anim) } // SCALINGS - if (anim->mNumScalingKeys > 1 && AllIdentical(anim->mScalingKeys,anim->mNumScalingKeys,configEpsilon)) - { + if (anim->mNumScalingKeys > 1 && AllIdentical(anim->mScalingKeys,anim->mNumScalingKeys,configEpsilon)) { aiVectorKey v = anim->mScalingKeys[0]; // Reallocate ... we need just ONE element, it makes no sense to reuse the array @@ -331,13 +323,14 @@ void FindInvalidDataProcess::ProcessAnimationChannel (aiNodeAnim* anim) anim->mScalingKeys[0] = v; i = 1; } - if (1 == i) + if ( 1 == i ) { ASSIMP_LOG_WARN("Simplified dummy tracks with just one key"); + } } // ------------------------------------------------------------------------------------------------ // Search a mesh for invalid contents -int FindInvalidDataProcess::ProcessMesh (aiMesh* pMesh) +int FindInvalidDataProcess::ProcessMesh(aiMesh* pMesh) { bool ret = false; std::vector dirtyMask(pMesh->mNumVertices, pMesh->mNumFaces != 0); @@ -360,18 +353,20 @@ int FindInvalidDataProcess::ProcessMesh (aiMesh* pMesh) } // process texture coordinates - for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS && pMesh->mTextureCoords[i]; ++i) { - if (ProcessArray(pMesh->mTextureCoords[i], pMesh->mNumVertices, "uvcoords", dirtyMask)) { - pMesh->mNumUVComponents[i] = 0; + if (!mIgnoreTexCoods) { + for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS && pMesh->mTextureCoords[i]; ++i) { + if (ProcessArray(pMesh->mTextureCoords[i], pMesh->mNumVertices, "uvcoords", dirtyMask)) { + pMesh->mNumUVComponents[i] = 0; - // delete all subsequent texture coordinate sets. - for (unsigned int a = i + 1; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) { - delete[] pMesh->mTextureCoords[a]; - pMesh->mTextureCoords[a] = NULL; - pMesh->mNumUVComponents[a] = 0; + // delete all subsequent texture coordinate sets. + for (unsigned int a = i + 1; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) { + delete[] pMesh->mTextureCoords[a]; + pMesh->mTextureCoords[a] = NULL; + pMesh->mNumUVComponents[a] = 0; + } + + ret = true; } - - ret = true; } } @@ -388,13 +383,11 @@ int FindInvalidDataProcess::ProcessMesh (aiMesh* pMesh) aiPrimitiveType_POLYGON & pMesh->mPrimitiveTypes) { // We need to update the lookup-table - for (unsigned int m = 0; m < pMesh->mNumFaces;++m) - { - const aiFace& f = pMesh->mFaces[m]; + for (unsigned int m = 0; m < pMesh->mNumFaces;++m) { + const aiFace& f = pMesh->mFaces[ m ]; if (f.mNumIndices < 3) { dirtyMask[f.mIndices[0]] = true; - if (f.mNumIndices == 2) { dirtyMask[f.mIndices[1]] = true; } @@ -403,7 +396,9 @@ int FindInvalidDataProcess::ProcessMesh (aiMesh* pMesh) } // Normals, tangents and bitangents are undefined for // the whole mesh (and should not even be there) - else return ret; + else { + return ret; + } } // Process mesh normals @@ -426,5 +421,4 @@ int FindInvalidDataProcess::ProcessMesh (aiMesh* pMesh) return ret ? 1 : 0; } - #endif // !! ASSIMP_BUILD_NO_FINDINVALIDDATA_PROCESS diff --git a/third_party/libassimp/code/FindInvalidDataProcess.h b/third_party/libassimp/code/PostProcessing/FindInvalidDataProcess.h similarity index 89% rename from third_party/libassimp/code/FindInvalidDataProcess.h rename to third_party/libassimp/code/PostProcessing/FindInvalidDataProcess.h index 00dfef1453..ce7375f34f 100644 --- a/third_party/libassimp/code/FindInvalidDataProcess.h +++ b/third_party/libassimp/code/PostProcessing/FindInvalidDataProcess.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -41,16 +41,20 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** @file Defines a post processing step to search an importer's output - for data that is obviously invalid */ + * for data that is obviously invalid + */ #ifndef AI_FINDINVALIDDATA_H_INC #define AI_FINDINVALIDDATA_H_INC -#include "BaseProcess.h" +#include "Common/BaseProcess.h" + #include #include struct aiMesh; + class FindInvalidDataProcessTest; + namespace Assimp { // --------------------------------------------------------------------------- @@ -59,15 +63,11 @@ namespace Assimp { * * Originally this was a workaround for some models written by Blender * which have zero normal vectors. */ -class ASSIMP_API FindInvalidDataProcess : public BaseProcess -{ +class ASSIMP_API FindInvalidDataProcess : public BaseProcess { public: - FindInvalidDataProcess(); ~FindInvalidDataProcess(); -public: - // ------------------------------------------------------------------- // bool IsActive( unsigned int pFlags) const; @@ -80,26 +80,25 @@ public: // Run the step void Execute( aiScene* pScene); -public: - // ------------------------------------------------------------------- - /** Executes the postprocessing step on the given mesh + /** Executes the post-processing step on the given mesh * @param pMesh The mesh to process. * @return 0 - nothing, 1 - removed sth, 2 - please delete me */ int ProcessMesh( aiMesh* pMesh); // ------------------------------------------------------------------- - /** Executes the postprocessing step on the given animation + /** Executes the post-processing step on the given animation * @param anim The animation to process. */ void ProcessAnimation (aiAnimation* anim); // ------------------------------------------------------------------- - /** Executes the postprocessing step on the given anim channel + /** Executes the post-processing step on the given anim channel * @param anim The animation channel to process.*/ void ProcessAnimationChannel (aiNodeAnim* anim); private: ai_real configEpsilon; + bool mIgnoreTexCoods; }; } // end of namespace Assimp diff --git a/third_party/libassimp/code/FixNormalsStep.cpp b/third_party/libassimp/code/PostProcessing/FixNormalsStep.cpp similarity index 99% rename from third_party/libassimp/code/FixNormalsStep.cpp rename to third_party/libassimp/code/PostProcessing/FixNormalsStep.cpp index 668b50c249..bbbe6899b4 100644 --- a/third_party/libassimp/code/FixNormalsStep.cpp +++ b/third_party/libassimp/code/PostProcessing/FixNormalsStep.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/FixNormalsStep.h b/third_party/libassimp/code/PostProcessing/FixNormalsStep.h similarity index 97% rename from third_party/libassimp/code/FixNormalsStep.h rename to third_party/libassimp/code/PostProcessing/FixNormalsStep.h index 389e6e1a6d..f60ce596a4 100644 --- a/third_party/libassimp/code/FixNormalsStep.h +++ b/third_party/libassimp/code/PostProcessing/FixNormalsStep.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -45,7 +45,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_FIXNORMALSPROCESS_H_INC #define AI_FIXNORMALSPROCESS_H_INC -#include "BaseProcess.h" +#include "Common/BaseProcess.h" struct aiMesh; diff --git a/third_party/libassimp/code/PostProcessing/GenBoundingBoxesProcess.cpp b/third_party/libassimp/code/PostProcessing/GenBoundingBoxesProcess.cpp new file mode 100644 index 0000000000..c013454fc3 --- /dev/null +++ b/third_party/libassimp/code/PostProcessing/GenBoundingBoxesProcess.cpp @@ -0,0 +1,115 @@ +/* +--------------------------------------------------------------------------- +Open Asset Import Library (assimp) +--------------------------------------------------------------------------- + +Copyright (c) 2006-2019, 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. +--------------------------------------------------------------------------- +*/ + +#ifndef ASSIMP_BUILD_NO_GENBOUNDINGBOXES_PROCESS + +#include "PostProcessing/GenBoundingBoxesProcess.h" + +#include +#include + +namespace Assimp { + +GenBoundingBoxesProcess::GenBoundingBoxesProcess() +: BaseProcess() { + +} + +GenBoundingBoxesProcess::~GenBoundingBoxesProcess() { + // empty +} + +bool GenBoundingBoxesProcess::IsActive(unsigned int pFlags) const { + return 0 != ( pFlags & aiProcess_GenBoundingBoxes ); +} + +void checkMesh(aiMesh* mesh, aiVector3D& min, aiVector3D& max) { + ai_assert(nullptr != mesh); + + if (0 == mesh->mNumVertices) { + return; + } + + for (unsigned int i = 0; i < mesh->mNumVertices; ++i) { + const aiVector3D &pos = mesh->mVertices[i]; + if (pos.x < min.x) { + min.x = pos.x; + } + if (pos.y < min.y) { + min.y = pos.y; + } + if (pos.z < min.z) { + min.z = pos.z; + } + + if (pos.x > max.x) { + max.x = pos.x; + } + if (pos.y > max.y) { + max.y = pos.y; + } + if (pos.z > max.z) { + max.z = pos.z; + } + } +} + +void GenBoundingBoxesProcess::Execute(aiScene* pScene) { + if (nullptr == pScene) { + return; + } + + for (unsigned int i = 0; i < pScene->mNumMeshes; ++i) { + aiMesh* mesh = pScene->mMeshes[i]; + if (nullptr == mesh) { + continue; + } + + aiVector3D min(999999, 999999, 999999), max(-999999, -999999, -999999); + checkMesh(mesh, min, max); + mesh->mAABB.mMin = min; + mesh->mAABB.mMax = max; + } +} + +} // Namespace Assimp + +#endif // ASSIMP_BUILD_NO_GENBOUNDINGBOXES_PROCESS diff --git a/third_party/libassimp/code/PostProcessing/GenBoundingBoxesProcess.h b/third_party/libassimp/code/PostProcessing/GenBoundingBoxesProcess.h new file mode 100644 index 0000000000..4b43c82a42 --- /dev/null +++ b/third_party/libassimp/code/PostProcessing/GenBoundingBoxesProcess.h @@ -0,0 +1,76 @@ +/* +--------------------------------------------------------------------------- +Open Asset Import Library (assimp) +--------------------------------------------------------------------------- + +Copyright (c) 2006-2019, 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 Defines a post-processing step to generate Axis-aligned bounding + * volumes for all meshes. + */ + +#pragma once + +#ifndef AI_GENBOUNDINGBOXESPROCESS_H_INC +#define AI_GENBOUNDINGBOXESPROCESS_H_INC + +#ifndef ASSIMP_BUILD_NO_GENBOUNDINGBOXES_PROCESS + +#include "Common/BaseProcess.h" + +namespace Assimp { + +/** Post-processing process to find axis-aligned bounding volumes for amm meshes + * used in a scene + */ +class ASSIMP_API GenBoundingBoxesProcess : public BaseProcess { +public: + /// The class constructor. + GenBoundingBoxesProcess(); + /// The class destructor. + ~GenBoundingBoxesProcess(); + /// Will return true, if aiProcess_GenBoundingBoxes is defined. + bool IsActive(unsigned int pFlags) const override; + /// The execution callback. + void Execute(aiScene* pScene) override; +}; + +} // Namespace Assimp + +#endif // #ifndef ASSIMP_BUILD_NO_GENBOUNDINGBOXES_PROCESS + +#endif // AI_GENBOUNDINGBOXESPROCESS_H_INC diff --git a/third_party/libassimp/code/GenFaceNormalsProcess.cpp b/third_party/libassimp/code/PostProcessing/GenFaceNormalsProcess.cpp similarity index 99% rename from third_party/libassimp/code/GenFaceNormalsProcess.cpp rename to third_party/libassimp/code/PostProcessing/GenFaceNormalsProcess.cpp index 43960ac3b1..028334dec7 100644 --- a/third_party/libassimp/code/GenFaceNormalsProcess.cpp +++ b/third_party/libassimp/code/PostProcessing/GenFaceNormalsProcess.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/GenFaceNormalsProcess.h b/third_party/libassimp/code/PostProcessing/GenFaceNormalsProcess.h similarity index 97% rename from third_party/libassimp/code/GenFaceNormalsProcess.h rename to third_party/libassimp/code/PostProcessing/GenFaceNormalsProcess.h index e2f41e07f9..c641fd6353 100644 --- a/third_party/libassimp/code/GenFaceNormalsProcess.h +++ b/third_party/libassimp/code/PostProcessing/GenFaceNormalsProcess.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -44,7 +44,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_GENFACENORMALPROCESS_H_INC #define AI_GENFACENORMALPROCESS_H_INC -#include "BaseProcess.h" +#include "Common/BaseProcess.h" #include namespace Assimp diff --git a/third_party/libassimp/code/GenVertexNormalsProcess.cpp b/third_party/libassimp/code/PostProcessing/GenVertexNormalsProcess.cpp similarity index 99% rename from third_party/libassimp/code/GenVertexNormalsProcess.cpp rename to third_party/libassimp/code/PostProcessing/GenVertexNormalsProcess.cpp index 1778ef513b..3f6c2f86bd 100644 --- a/third_party/libassimp/code/GenVertexNormalsProcess.cpp +++ b/third_party/libassimp/code/PostProcessing/GenVertexNormalsProcess.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/GenVertexNormalsProcess.h b/third_party/libassimp/code/PostProcessing/GenVertexNormalsProcess.h similarity index 93% rename from third_party/libassimp/code/GenVertexNormalsProcess.h rename to third_party/libassimp/code/PostProcessing/GenVertexNormalsProcess.h index 2efafa3029..2ceee17e85 100644 --- a/third_party/libassimp/code/GenVertexNormalsProcess.h +++ b/third_party/libassimp/code/PostProcessing/GenVertexNormalsProcess.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -45,24 +45,24 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_GENVERTEXNORMALPROCESS_H_INC #define AI_GENVERTEXNORMALPROCESS_H_INC -#include "BaseProcess.h" +#include "Common/assbin_chunks.h" +#include "Common/BaseProcess.h" + #include +// Forward declarations class GenNormalsTest; namespace Assimp { // --------------------------------------------------------------------------- -/** The GenFaceNormalsProcess computes vertex normals for all vertizes +/** The GenFaceNormalsProcess computes vertex normals for all vertices */ -class ASSIMP_API GenVertexNormalsProcess : public BaseProcess -{ +class ASSIMP_API GenVertexNormalsProcess : public BaseProcess { public: - GenVertexNormalsProcess(); ~GenVertexNormalsProcess(); -public: // ------------------------------------------------------------------- /** Returns whether the processing step is present in the given flag. * @param pFlags The processing flags the importer was called with. @@ -88,13 +88,10 @@ public: // setter for configMaxAngle - inline void SetMaxSmoothAngle(ai_real f) - { + inline void SetMaxSmoothAngle(ai_real f) { configMaxAngle =f; } -public: - // ------------------------------------------------------------------- /** Computes normals for a specific mesh * @param pcMesh Mesh @@ -104,7 +101,6 @@ public: bool GenMeshVertexNormals (aiMesh* pcMesh, unsigned int meshIndex); private: - /** Configuration option: maximum smoothing angle, in radians*/ ai_real configMaxAngle; mutable bool force_ = false; diff --git a/third_party/libassimp/code/ImproveCacheLocality.cpp b/third_party/libassimp/code/PostProcessing/ImproveCacheLocality.cpp similarity index 89% rename from third_party/libassimp/code/ImproveCacheLocality.cpp rename to third_party/libassimp/code/PostProcessing/ImproveCacheLocality.cpp index adcbc92fed..d0a016fa42 100644 --- a/third_party/libassimp/code/ImproveCacheLocality.cpp +++ b/third_party/libassimp/code/PostProcessing/ImproveCacheLocality.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -45,14 +45,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* The algorithm is roughly basing on this paper: * http://www.cs.princeton.edu/gfx/pubs/Sander_2007_%3ETR/tipsy.pdf - * .. although overdraw rduction isn't implemented yet ... + * .. although overdraw reduction isn't implemented yet ... */ - - // internal headers -#include "ImproveCacheLocality.h" -#include "VertexTriangleAdjacency.h" +#include "PostProcessing/ImproveCacheLocality.h" +#include "Common/VertexTriangleAdjacency.h" + #include #include #include @@ -64,36 +63,33 @@ using namespace Assimp; // ------------------------------------------------------------------------------------------------ // Constructor to be privately used by Importer -ImproveCacheLocalityProcess::ImproveCacheLocalityProcess() { - configCacheDepth = PP_ICL_PTCACHE_SIZE; +ImproveCacheLocalityProcess::ImproveCacheLocalityProcess() +: mConfigCacheDepth(PP_ICL_PTCACHE_SIZE) { + // empty } // ------------------------------------------------------------------------------------------------ // Destructor, private as well -ImproveCacheLocalityProcess::~ImproveCacheLocalityProcess() -{ +ImproveCacheLocalityProcess::~ImproveCacheLocalityProcess() { // nothing to do here } // ------------------------------------------------------------------------------------------------ // Returns whether the processing step is present in the given flag field. -bool ImproveCacheLocalityProcess::IsActive( unsigned int pFlags) const -{ +bool ImproveCacheLocalityProcess::IsActive( unsigned int pFlags) const { return (pFlags & aiProcess_ImproveCacheLocality) != 0; } // ------------------------------------------------------------------------------------------------ // Setup configuration -void ImproveCacheLocalityProcess::SetupProperties(const Importer* pImp) -{ +void ImproveCacheLocalityProcess::SetupProperties(const Importer* pImp) { // AI_CONFIG_PP_ICL_PTCACHE_SIZE controls the target cache size for the optimizer - configCacheDepth = pImp->GetPropertyInteger(AI_CONFIG_PP_ICL_PTCACHE_SIZE,PP_ICL_PTCACHE_SIZE); + mConfigCacheDepth = pImp->GetPropertyInteger(AI_CONFIG_PP_ICL_PTCACHE_SIZE,PP_ICL_PTCACHE_SIZE); } // ------------------------------------------------------------------------------------------------ // Executes the post processing step on the given imported data. -void ImproveCacheLocalityProcess::Execute( aiScene* pScene) -{ +void ImproveCacheLocalityProcess::Execute( aiScene* pScene) { if (!pScene->mNumMeshes) { ASSIMP_LOG_DEBUG("ImproveCacheLocalityProcess skipped; there are no meshes"); return; @@ -103,7 +99,7 @@ void ImproveCacheLocalityProcess::Execute( aiScene* pScene) float out = 0.f; unsigned int numf = 0, numm = 0; - for( unsigned int a = 0; a < pScene->mNumMeshes; a++){ + for( unsigned int a = 0; a < pScene->mNumMeshes; ++a ){ const float res = ProcessMesh( pScene->mMeshes[a],a); if (res) { numf += pScene->mMeshes[a]->mNumFaces; @@ -112,51 +108,50 @@ void ImproveCacheLocalityProcess::Execute( aiScene* pScene) } } if (!DefaultLogger::isNullLogger()) { - ASSIMP_LOG_INFO_F("Cache relevant are ", numm, " meshes (", numf," faces). Average output ACMR is ", out / numf ); + if (numf > 0) { + ASSIMP_LOG_INFO_F("Cache relevant are ", numm, " meshes (", numf, " faces). Average output ACMR is ", out / numf); + } ASSIMP_LOG_DEBUG("ImproveCacheLocalityProcess finished. "); } } // ------------------------------------------------------------------------------------------------ // Improves the cache coherency of a specific mesh -float ImproveCacheLocalityProcess::ProcessMesh( aiMesh* pMesh, unsigned int meshNum) -{ +ai_real ImproveCacheLocalityProcess::ProcessMesh( aiMesh* pMesh, unsigned int meshNum) { // TODO: rewrite this to use std::vector or boost::shared_array - ai_assert(NULL != pMesh); + ai_assert(nullptr != pMesh); // Check whether the input data is valid // - there must be vertices and faces // - all faces must be triangulated or we can't operate on them if (!pMesh->HasFaces() || !pMesh->HasPositions()) - return 0.f; + return static_cast(0.f); if (pMesh->mPrimitiveTypes != aiPrimitiveType_TRIANGLE) { ASSIMP_LOG_ERROR("This algorithm works on triangle meshes only"); - return 0.f; + return static_cast(0.f); } - if(pMesh->mNumVertices <= configCacheDepth) { - return 0.f; + if(pMesh->mNumVertices <= mConfigCacheDepth) { + return static_cast(0.f); } - float fACMR = 3.f; + ai_real fACMR = 3.f; const aiFace* const pcEnd = pMesh->mFaces+pMesh->mNumFaces; // Input ACMR is for logging purposes only if (!DefaultLogger::isNullLogger()) { - unsigned int* piFIFOStack = new unsigned int[configCacheDepth]; - memset(piFIFOStack,0xff,configCacheDepth*sizeof(unsigned int)); + unsigned int* piFIFOStack = new unsigned int[mConfigCacheDepth]; + memset(piFIFOStack,0xff,mConfigCacheDepth*sizeof(unsigned int)); unsigned int* piCur = piFIFOStack; - const unsigned int* const piCurEnd = piFIFOStack + configCacheDepth; + const unsigned int* const piCurEnd = piFIFOStack + mConfigCacheDepth; // count the number of cache misses unsigned int iCacheMisses = 0; for (const aiFace* pcFace = pMesh->mFaces;pcFace != pcEnd;++pcFace) { - for (unsigned int qq = 0; qq < 3;++qq) { bool bInCache = false; - for (unsigned int* pp = piFIFOStack;pp < piCurEnd;++pp) { if (*pp == pcFace->mIndices[qq]) { // the vertex is in cache @@ -174,7 +169,7 @@ float ImproveCacheLocalityProcess::ProcessMesh( aiMesh* pMesh, unsigned int mesh } } delete[] piFIFOStack; - fACMR = (float)iCacheMisses / pMesh->mNumFaces; + fACMR = (ai_real) iCacheMisses / pMesh->mNumFaces; if (3.0 == fACMR) { char szBuff[128]; // should be sufficiently large in every case @@ -183,7 +178,7 @@ float ImproveCacheLocalityProcess::ProcessMesh( aiMesh* pMesh, unsigned int mesh // smaller than 3.0 ... ai_snprintf(szBuff,128,"Mesh %u: Not suitable for vcache optimization",meshNum); ASSIMP_LOG_WARN(szBuff); - return 0.f; + return static_cast(0.f); } } @@ -256,7 +251,7 @@ float ImproveCacheLocalityProcess::ProcessMesh( aiMesh* pMesh, unsigned int mesh int ivdx = 0; int ics = 1; - int iStampCnt = configCacheDepth+1; + int iStampCnt = mConfigCacheDepth+1; while (ivdx >= 0) { unsigned int icnt = piNumTriPtrNoModify[ivdx]; @@ -292,7 +287,7 @@ float ImproveCacheLocalityProcess::ProcessMesh( aiMesh* pMesh, unsigned int mesh *piCSIter++ = dp; // if the vertex is not yet in cache, set its cache count - if (iStampCnt-piCachingStamps[dp] > configCacheDepth) { + if (iStampCnt-piCachingStamps[dp] > mConfigCacheDepth) { piCachingStamps[dp] = iStampCnt++; ++iCacheMisses; } @@ -317,7 +312,7 @@ float ImproveCacheLocalityProcess::ProcessMesh( aiMesh* pMesh, unsigned int mesh // will the vertex be in cache, even after fanning occurs? unsigned int tmp; - if ((tmp = iStampCnt-piCachingStamps[dp]) + 2*piNumTriPtr[dp] <= configCacheDepth) { + if ((tmp = iStampCnt-piCachingStamps[dp]) + 2*piNumTriPtr[dp] <= mConfigCacheDepth) { priority = tmp; } @@ -354,7 +349,7 @@ float ImproveCacheLocalityProcess::ProcessMesh( aiMesh* pMesh, unsigned int mesh } } } - float fACMR2 = 0.0f; + ai_real fACMR2 = 0.0f; if (!DefaultLogger::isNullLogger()) { fACMR2 = (float)iCacheMisses / pMesh->mNumFaces; diff --git a/third_party/libassimp/code/ImproveCacheLocality.h b/third_party/libassimp/code/PostProcessing/ImproveCacheLocality.h similarity index 95% rename from third_party/libassimp/code/ImproveCacheLocality.h rename to third_party/libassimp/code/PostProcessing/ImproveCacheLocality.h index 18eb5e4605..de25ecd9fb 100644 --- a/third_party/libassimp/code/ImproveCacheLocality.h +++ b/third_party/libassimp/code/PostProcessing/ImproveCacheLocality.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -45,7 +45,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_IMPROVECACHELOCALITY_H_INC #define AI_IMPROVECACHELOCALITY_H_INC -#include "BaseProcess.h" +#include "Common/BaseProcess.h" + #include struct aiMesh; @@ -87,12 +88,12 @@ protected: * @param pMesh The mesh to process. * @param meshNum Index of the mesh to process */ - float ProcessMesh( aiMesh* pMesh, unsigned int meshNum); + ai_real ProcessMesh( aiMesh* pMesh, unsigned int meshNum); private: //! Configuration parameter: specifies the size of the cache to //! optimize the vertex data for. - unsigned int configCacheDepth; + unsigned int mConfigCacheDepth; }; } // end of namespace Assimp diff --git a/third_party/libassimp/code/JoinVerticesProcess.cpp b/third_party/libassimp/code/PostProcessing/JoinVerticesProcess.cpp similarity index 93% rename from third_party/libassimp/code/JoinVerticesProcess.cpp rename to third_party/libassimp/code/PostProcessing/JoinVerticesProcess.cpp index b91f440484..f121fc60d3 100644 --- a/third_party/libassimp/code/JoinVerticesProcess.cpp +++ b/third_party/libassimp/code/PostProcessing/JoinVerticesProcess.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -431,31 +431,6 @@ int JoinVerticesProcess::ProcessMesh( aiMesh* pMesh, unsigned int meshIndex) bone->mWeights = new aiVertexWeight[bone->mNumWeights]; memcpy( bone->mWeights, &newWeights[0], bone->mNumWeights * sizeof( aiVertexWeight)); } - else { - - /* NOTE: - * - * In the algorithm above we're assuming that there are no vertices - * with a different bone weight setup at the same position. That wouldn't - * make sense, but it is not absolutely impossible. SkeletonMeshBuilder - * for example generates such input data if two skeleton points - * share the same position. Again this doesn't make sense but is - * reality for some model formats (MD5 for example uses these special - * nodes as attachment tags for its weapons). - * - * Then it is possible that a bone has no weights anymore .... as a quick - * workaround, we're just removing these bones. If they're animated, - * model geometry might be modified but at least there's no risk of a crash. - */ - delete bone; - --pMesh->mNumBones; - for (unsigned int n = a; n < pMesh->mNumBones; ++n) { - pMesh->mBones[n] = pMesh->mBones[n+1]; - } - - --a; - ASSIMP_LOG_WARN("Removing bone -> no weights remaining"); - } } return pMesh->mNumVertices; } diff --git a/third_party/libassimp/code/JoinVerticesProcess.h b/third_party/libassimp/code/PostProcessing/JoinVerticesProcess.h similarity index 96% rename from third_party/libassimp/code/JoinVerticesProcess.h rename to third_party/libassimp/code/PostProcessing/JoinVerticesProcess.h index a7366efbea..e017ae62db 100644 --- a/third_party/libassimp/code/JoinVerticesProcess.h +++ b/third_party/libassimp/code/PostProcessing/JoinVerticesProcess.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -45,7 +45,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_JOINVERTICESPROCESS_H_INC #define AI_JOINVERTICESPROCESS_H_INC -#include "BaseProcess.h" +#include "Common/BaseProcess.h" + #include struct aiMesh; @@ -61,13 +62,11 @@ namespace Assimp * erases all but one of the copies. This usually reduces the number of vertices * in a mesh by a serious amount and is the standard form to render a mesh. */ -class ASSIMP_API JoinVerticesProcess : public BaseProcess -{ +class ASSIMP_API JoinVerticesProcess : public BaseProcess { public: JoinVerticesProcess(); ~JoinVerticesProcess(); -public: // ------------------------------------------------------------------- /** Returns whether the processing step is present in the given flag field. * @param pFlags The processing flags the importer was called with. A bitwise @@ -83,15 +82,12 @@ public: */ void Execute( aiScene* pScene); -public: // ------------------------------------------------------------------- /** Unites identical vertices in the given mesh. * @param pMesh The mesh to process. * @param meshIndex Index of the mesh to process */ int ProcessMesh( aiMesh* pMesh, unsigned int meshIndex); - -private: }; } // end of namespace Assimp diff --git a/third_party/libassimp/code/LimitBoneWeightsProcess.cpp b/third_party/libassimp/code/PostProcessing/LimitBoneWeightsProcess.cpp similarity index 99% rename from third_party/libassimp/code/LimitBoneWeightsProcess.cpp rename to third_party/libassimp/code/PostProcessing/LimitBoneWeightsProcess.cpp index cc87e407c4..d560f19287 100644 --- a/third_party/libassimp/code/LimitBoneWeightsProcess.cpp +++ b/third_party/libassimp/code/PostProcessing/LimitBoneWeightsProcess.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/LimitBoneWeightsProcess.h b/third_party/libassimp/code/PostProcessing/LimitBoneWeightsProcess.h similarity index 92% rename from third_party/libassimp/code/LimitBoneWeightsProcess.h rename to third_party/libassimp/code/PostProcessing/LimitBoneWeightsProcess.h index 2161b89a86..73c2a68d53 100644 --- a/third_party/libassimp/code/LimitBoneWeightsProcess.h +++ b/third_party/libassimp/code/PostProcessing/LimitBoneWeightsProcess.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -44,14 +44,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_LIMITBONEWEIGHTSPROCESS_H_INC #define AI_LIMITBONEWEIGHTSPROCESS_H_INC -#include "BaseProcess.h" +#include "Common/BaseProcess.h" +// Forward declarations struct aiMesh; class LimitBoneWeightsTest; -namespace Assimp -{ +namespace Assimp { // NOTE: If you change these limits, don't forget to change the // corresponding values in all Assimp ports @@ -72,14 +72,11 @@ namespace Assimp * The other weights on this bone are then renormalized to assure the sum weight * to be 1. */ -class ASSIMP_API LimitBoneWeightsProcess : public BaseProcess -{ +class ASSIMP_API LimitBoneWeightsProcess : public BaseProcess { public: - LimitBoneWeightsProcess(); ~LimitBoneWeightsProcess(); -public: // ------------------------------------------------------------------- /** Returns whether the processing step is present in the given flag. * @param pFlags The processing flags the importer was called with. @@ -96,8 +93,6 @@ public: */ void SetupProperties(const Importer* pImp); -public: - // ------------------------------------------------------------------- /** Limits the bone weight count for all vertices in the given mesh. * @param pMesh The mesh to process. @@ -111,34 +106,29 @@ public: */ void Execute( aiScene* pScene); - -public: - // ------------------------------------------------------------------- /** Describes a bone weight on a vertex */ - struct Weight - { + struct Weight { unsigned int mBone; ///< Index of the bone float mWeight; ///< Weight of that bone on this vertex Weight() AI_NO_EXCEPT : mBone(0) - , mWeight(0.0f) - { } + , mWeight(0.0f) { + // empty + } Weight( unsigned int pBone, float pWeight) - { - mBone = pBone; - mWeight = pWeight; + : mBone(pBone) + , mWeight(pWeight) { + // empty } /** Comparison operator to sort bone weights by descending weight */ - bool operator < (const Weight& pWeight) const - { + bool operator < (const Weight& pWeight) const { return mWeight > pWeight.mWeight; } }; -public: /** Maximum number of bones influencing any single vertex. */ unsigned int mMaxWeights; }; diff --git a/third_party/libassimp/code/MakeVerboseFormat.cpp b/third_party/libassimp/code/PostProcessing/MakeVerboseFormat.cpp similarity index 88% rename from third_party/libassimp/code/MakeVerboseFormat.cpp rename to third_party/libassimp/code/PostProcessing/MakeVerboseFormat.cpp index b6f5cabd98..41f50a5ba5 100644 --- a/third_party/libassimp/code/MakeVerboseFormat.cpp +++ b/third_party/libassimp/code/PostProcessing/MakeVerboseFormat.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -224,3 +224,32 @@ bool MakeVerboseFormatProcess::MakeVerboseFormat(aiMesh* pcMesh) } return (pcMesh->mNumVertices != iOldNumVertices); } + + +// ------------------------------------------------------------------------------------------------ +bool IsMeshInVerboseFormat(const aiMesh* mesh) { + // avoid slow vector specialization + std::vector seen(mesh->mNumVertices,0); + for(unsigned int i = 0; i < mesh->mNumFaces; ++i) { + const aiFace& f = mesh->mFaces[i]; + for(unsigned int j = 0; j < f.mNumIndices; ++j) { + if(++seen[f.mIndices[j]] == 2) { + // found a duplicate index + return false; + } + } + } + + return true; +} + +// ------------------------------------------------------------------------------------------------ +bool MakeVerboseFormatProcess::IsVerboseFormat(const aiScene* pScene) { + for(unsigned int i = 0; i < pScene->mNumMeshes; ++i) { + if(!IsMeshInVerboseFormat(pScene->mMeshes[i])) { + return false; + } + } + + return true; +} diff --git a/third_party/libassimp/code/MakeVerboseFormat.h b/third_party/libassimp/code/PostProcessing/MakeVerboseFormat.h similarity index 91% rename from third_party/libassimp/code/MakeVerboseFormat.h rename to third_party/libassimp/code/PostProcessing/MakeVerboseFormat.h index 292d9bea67..8565d5933a 100644 --- a/third_party/libassimp/code/MakeVerboseFormat.h +++ b/third_party/libassimp/code/PostProcessing/MakeVerboseFormat.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -46,7 +46,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_MAKEVERBOSEFORMAT_H_INC #define AI_MAKEVERBOSEFORMAT_H_INC -#include "BaseProcess.h" +#include "Common/BaseProcess.h" + struct aiMesh; namespace Assimp { @@ -93,6 +94,13 @@ public: * @param pScene The imported data to work at. */ void Execute( aiScene* pScene); +public: + + // ------------------------------------------------------------------- + /** Checks whether the scene is already in verbose format. + * @param pScene The data to check. + * @return true if the scene is already in verbose format. */ + static bool IsVerboseFormat(const aiScene* pScene); private: diff --git a/third_party/libassimp/code/OptimizeGraph.cpp b/third_party/libassimp/code/PostProcessing/OptimizeGraph.cpp similarity index 99% rename from third_party/libassimp/code/OptimizeGraph.cpp rename to third_party/libassimp/code/PostProcessing/OptimizeGraph.cpp index 59a764d5cd..5db51f58b6 100644 --- a/third_party/libassimp/code/OptimizeGraph.cpp +++ b/third_party/libassimp/code/PostProcessing/OptimizeGraph.cpp @@ -3,9 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team - - +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/OptimizeGraph.h b/third_party/libassimp/code/PostProcessing/OptimizeGraph.h similarity index 92% rename from third_party/libassimp/code/OptimizeGraph.h rename to third_party/libassimp/code/PostProcessing/OptimizeGraph.h index 6781ec534e..82cc5db3fe 100644 --- a/third_party/libassimp/code/OptimizeGraph.h +++ b/third_party/libassimp/code/PostProcessing/OptimizeGraph.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -46,13 +46,18 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_OPTIMIZEGRAPHPROCESS_H_INC #define AI_OPTIMIZEGRAPHPROCESS_H_INC -#include "BaseProcess.h" -#include "ProcessHelper.h" +#include "Common/BaseProcess.h" +#include "PostProcessing/ProcessHelper.h" + #include + #include +// Forward declarations struct aiMesh; + class OptimizeGraphProcessTest; + namespace Assimp { // ----------------------------------------------------------------------------- @@ -64,14 +69,11 @@ namespace Assimp { * @see aiProcess_OptimizeGraph for a detailed description of the * algorithm being applied. */ -class OptimizeGraphProcess : public BaseProcess -{ +class OptimizeGraphProcess : public BaseProcess { public: - OptimizeGraphProcess(); ~OptimizeGraphProcess(); -public: // ------------------------------------------------------------------- bool IsActive( unsigned int pFlags) const; @@ -81,14 +83,12 @@ public: // ------------------------------------------------------------------- void SetupProperties(const Importer* pImp); - // ------------------------------------------------------------------- /** @brief Add a list of node names to be locked and not modified. * @param in List of nodes. See #AI_CONFIG_PP_OG_EXCLUDE_LIST for * format explanations. */ - inline void AddLockedNodeList(std::string& in) - { + inline void AddLockedNodeList(std::string& in) { ConvertListToStrings (in,locked_nodes); } @@ -96,8 +96,7 @@ public: /** @brief Add another node to be locked and not modified. * @param name Name to be locked */ - inline void AddLockedNode(std::string& name) - { + inline void AddLockedNode(std::string& name) { locked_nodes.push_back(name); } @@ -105,25 +104,21 @@ public: /** @brief Remove a node from the list of locked nodes. * @param name Name to be unlocked */ - inline void RemoveLockedNode(std::string& name) - { + inline void RemoveLockedNode(std::string& name) { locked_nodes.remove(name); } protected: - void CollectNewChildren(aiNode* nd, std::list& nodes); void FindInstancedMeshes (aiNode* pNode); private: - #ifdef AI_OG_USE_HASHING typedef std::set LockedSetType; #else typedef std::set LockedSetType; #endif - //! Scene we're working with aiScene* mScene; diff --git a/third_party/libassimp/code/OptimizeMeshes.cpp b/third_party/libassimp/code/PostProcessing/OptimizeMeshes.cpp similarity index 99% rename from third_party/libassimp/code/OptimizeMeshes.cpp rename to third_party/libassimp/code/PostProcessing/OptimizeMeshes.cpp index 25575b0490..3f6765f6ca 100644 --- a/third_party/libassimp/code/OptimizeMeshes.cpp +++ b/third_party/libassimp/code/PostProcessing/OptimizeMeshes.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/OptimizeMeshes.h b/third_party/libassimp/code/PostProcessing/OptimizeMeshes.h similarity index 97% rename from third_party/libassimp/code/OptimizeMeshes.h rename to third_party/libassimp/code/PostProcessing/OptimizeMeshes.h index 3ebe60cd83..dec4ab52de 100644 --- a/third_party/libassimp/code/OptimizeMeshes.h +++ b/third_party/libassimp/code/PostProcessing/OptimizeMeshes.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -46,8 +46,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_OPTIMIZEMESHESPROCESS_H_INC #define AI_OPTIMIZEMESHESPROCESS_H_INC -#include "BaseProcess.h" +#include "Common/BaseProcess.h" + #include + #include struct aiMesh; @@ -64,16 +66,14 @@ namespace Assimp { * * @note Instanced meshes are currently not processed. */ -class OptimizeMeshesProcess : public BaseProcess -{ +class OptimizeMeshesProcess : public BaseProcess { public: /// @brief The class constructor. OptimizeMeshesProcess(); - /// @brief The class destcructor, + /// @brief The class destructor. ~OptimizeMeshesProcess(); - /** @brief Internal utility to store additional mesh info */ struct MeshInfo { diff --git a/third_party/libassimp/code/PretransformVertices.cpp b/third_party/libassimp/code/PostProcessing/PretransformVertices.cpp similarity index 99% rename from third_party/libassimp/code/PretransformVertices.cpp rename to third_party/libassimp/code/PostProcessing/PretransformVertices.cpp index 9745abd60d..52001a0578 100644 --- a/third_party/libassimp/code/PretransformVertices.cpp +++ b/third_party/libassimp/code/PostProcessing/PretransformVertices.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/PretransformVertices.h b/third_party/libassimp/code/PostProcessing/PretransformVertices.h similarity index 96% rename from third_party/libassimp/code/PretransformVertices.h rename to third_party/libassimp/code/PostProcessing/PretransformVertices.h index a8196289d8..b2982951e0 100644 --- a/third_party/libassimp/code/PretransformVertices.h +++ b/third_party/libassimp/code/PostProcessing/PretransformVertices.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -47,13 +47,18 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_PRETRANSFORMVERTICES_H_INC #define AI_PRETRANSFORMVERTICES_H_INC -#include "BaseProcess.h" +#include "Common/BaseProcess.h" + #include + #include #include +// Forward declarations struct aiNode; + class PretransformVerticesTest; + namespace Assimp { // --------------------------------------------------------------------------- @@ -80,10 +85,10 @@ public: // ------------------------------------------------------------------- /** @brief Toggle the 'keep hierarchy' option - * @param d hm ... difficult to guess what this means, hu!? + * @param keep true for keep configuration. */ - void KeepHierarchy(bool d) { - configKeepHierarchy = d; + void KeepHierarchy(bool keep) { + configKeepHierarchy = keep; } // ------------------------------------------------------------------- @@ -148,8 +153,6 @@ private: // Build reference counters for all meshes void BuildMeshRefCountArray(aiNode* nd, unsigned int * refs); - - //! Configuration option: keep scene hierarchy as long as possible bool configKeepHierarchy; bool configNormalize; diff --git a/third_party/libassimp/code/ProcessHelper.cpp b/third_party/libassimp/code/PostProcessing/ProcessHelper.cpp similarity index 99% rename from third_party/libassimp/code/ProcessHelper.cpp rename to third_party/libassimp/code/PostProcessing/ProcessHelper.cpp index 7f3e4ba729..59869fdff7 100644 --- a/third_party/libassimp/code/ProcessHelper.cpp +++ b/third_party/libassimp/code/PostProcessing/ProcessHelper.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/ProcessHelper.h b/third_party/libassimp/code/PostProcessing/ProcessHelper.h similarity index 99% rename from third_party/libassimp/code/ProcessHelper.h rename to third_party/libassimp/code/PostProcessing/ProcessHelper.h index dcf71e8532..0afcc41420 100644 --- a/third_party/libassimp/code/ProcessHelper.h +++ b/third_party/libassimp/code/PostProcessing/ProcessHelper.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -51,7 +51,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include "BaseProcess.h" +#include "Common/BaseProcess.h" #include #include diff --git a/third_party/libassimp/code/RemoveRedundantMaterials.cpp b/third_party/libassimp/code/PostProcessing/RemoveRedundantMaterials.cpp similarity index 96% rename from third_party/libassimp/code/RemoveRedundantMaterials.cpp rename to third_party/libassimp/code/PostProcessing/RemoveRedundantMaterials.cpp index 7194d3c8ee..49ec8f5c47 100644 --- a/third_party/libassimp/code/RemoveRedundantMaterials.cpp +++ b/third_party/libassimp/code/PostProcessing/RemoveRedundantMaterials.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -49,7 +49,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "RemoveRedundantMaterials.h" #include #include "ProcessHelper.h" -#include "MaterialSystem.h" +#include "Material/MaterialSystem.h" #include using namespace Assimp; @@ -57,7 +57,7 @@ using namespace Assimp; // ------------------------------------------------------------------------------------------------ // Constructor to be privately used by Importer RemoveRedundantMatsProcess::RemoveRedundantMatsProcess() -: configFixedMaterials() { +: mConfigFixedMaterials() { // nothing to do here } @@ -80,7 +80,7 @@ bool RemoveRedundantMatsProcess::IsActive( unsigned int pFlags) const void RemoveRedundantMatsProcess::SetupProperties(const Importer* pImp) { // Get value of AI_CONFIG_PP_RRM_EXCLUDE_LIST - configFixedMaterials = pImp->GetPropertyString(AI_CONFIG_PP_RRM_EXCLUDE_LIST,""); + mConfigFixedMaterials = pImp->GetPropertyString(AI_CONFIG_PP_RRM_EXCLUDE_LIST,""); } // ------------------------------------------------------------------------------------------------ @@ -100,10 +100,10 @@ void RemoveRedundantMatsProcess::Execute( aiScene* pScene) // If a list of materials to be excluded was given, match the list with // our imported materials and 'salt' all positive matches to ensure that // we get unique hashes later. - if (configFixedMaterials.length()) { + if (mConfigFixedMaterials.length()) { std::list strings; - ConvertListToStrings(configFixedMaterials,strings); + ConvertListToStrings(mConfigFixedMaterials,strings); for (unsigned int i = 0; i < pScene->mNumMaterials;++i) { aiMaterial* mat = pScene->mMaterials[i]; diff --git a/third_party/libassimp/code/RemoveRedundantMaterials.h b/third_party/libassimp/code/PostProcessing/RemoveRedundantMaterials.h similarity index 91% rename from third_party/libassimp/code/RemoveRedundantMaterials.h rename to third_party/libassimp/code/PostProcessing/RemoveRedundantMaterials.h index 314bbf3459..1f32a0abfb 100644 --- a/third_party/libassimp/code/RemoveRedundantMaterials.h +++ b/third_party/libassimp/code/PostProcessing/RemoveRedundantMaterials.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -46,7 +46,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_REMOVEREDUNDANTMATERIALS_H_INC #define AI_REMOVEREDUNDANTMATERIALS_H_INC -#include "BaseProcess.h" +#include "Common/BaseProcess.h" #include class RemoveRedundantMatsTest; @@ -57,8 +57,7 @@ namespace Assimp { /** RemoveRedundantMatsProcess: Post-processing step to remove redundant * materials from the imported scene. */ -class ASSIMP_API RemoveRedundantMatsProcess : public BaseProcess -{ +class ASSIMP_API RemoveRedundantMatsProcess : public BaseProcess { public: /// The default class constructor. RemoveRedundantMatsProcess(); @@ -66,7 +65,6 @@ public: /// The class destructor. ~RemoveRedundantMatsProcess(); -public: // ------------------------------------------------------------------- // Check whether step is active bool IsActive( unsigned int pFlags) const; @@ -79,27 +77,25 @@ public: // Setup import settings void SetupProperties(const Importer* pImp); - // ------------------------------------------------------------------- - /** @brief Set list of fixed (unmutable) materials + /** @brief Set list of fixed (inmutable) materials * @param fixed See #AI_CONFIG_PP_RRM_EXCLUDE_LIST */ void SetFixedMaterialsString(const std::string& fixed = "") { - configFixedMaterials = fixed; + mConfigFixedMaterials = fixed; } // ------------------------------------------------------------------- - /** @brief Get list of fixed (unmutable) materials + /** @brief Get list of fixed (inmutable) materials * @return See #AI_CONFIG_PP_RRM_EXCLUDE_LIST */ const std::string& GetFixedMaterialsString() const { - return configFixedMaterials; + return mConfigFixedMaterials; } private: - //! Configuration option: list of all fixed materials - std::string configFixedMaterials; + std::string mConfigFixedMaterials; }; } // end of namespace Assimp diff --git a/third_party/libassimp/code/RemoveVCProcess.cpp b/third_party/libassimp/code/PostProcessing/RemoveVCProcess.cpp similarity index 99% rename from third_party/libassimp/code/RemoveVCProcess.cpp rename to third_party/libassimp/code/PostProcessing/RemoveVCProcess.cpp index 81249eab25..99fd47a3aa 100644 --- a/third_party/libassimp/code/RemoveVCProcess.cpp +++ b/third_party/libassimp/code/PostProcessing/RemoveVCProcess.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/RemoveVCProcess.h b/third_party/libassimp/code/PostProcessing/RemoveVCProcess.h similarity index 98% rename from third_party/libassimp/code/RemoveVCProcess.h rename to third_party/libassimp/code/PostProcessing/RemoveVCProcess.h index 597de8584f..7bb21a8330 100644 --- a/third_party/libassimp/code/RemoveVCProcess.h +++ b/third_party/libassimp/code/PostProcessing/RemoveVCProcess.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -44,7 +44,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_REMOVEVCPROCESS_H_INCLUDED #define AI_REMOVEVCPROCESS_H_INCLUDED -#include "BaseProcess.h" +#include "Common/BaseProcess.h" + #include class RemoveVCProcessTest; diff --git a/third_party/libassimp/code/PostProcessing/ScaleProcess.cpp b/third_party/libassimp/code/PostProcessing/ScaleProcess.cpp new file mode 100644 index 0000000000..ac770c41f2 --- /dev/null +++ b/third_party/libassimp/code/PostProcessing/ScaleProcess.cpp @@ -0,0 +1,208 @@ +/* +Open Asset Import Library (assimp) +---------------------------------------------------------------------- + +Copyright (c) 2006-2019, 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 "ScaleProcess.h" + +#include +#include +#include + +namespace Assimp { + +ScaleProcess::ScaleProcess() +: BaseProcess() +, mScale( AI_CONFIG_GLOBAL_SCALE_FACTOR_DEFAULT ) { +} + +ScaleProcess::~ScaleProcess() { + // empty +} + +void ScaleProcess::setScale( ai_real scale ) { + mScale = scale; +} + +ai_real ScaleProcess::getScale() const { + return mScale; +} + +bool ScaleProcess::IsActive( unsigned int pFlags ) const { + return ( pFlags & aiProcess_GlobalScale ) != 0; +} + +void ScaleProcess::SetupProperties( const Importer* pImp ) { + // User scaling + mScale = pImp->GetPropertyFloat( AI_CONFIG_GLOBAL_SCALE_FACTOR_KEY, 1.0f ); + + // File scaling * Application Scaling + float importerScale = pImp->GetPropertyFloat( AI_CONFIG_APP_SCALE_KEY, 1.0f ); + + // apply scale to the scale + // helps prevent bugs with backward compatibility for anyone using normal scaling. + mScale *= importerScale; +} + +void ScaleProcess::Execute( aiScene* pScene ) { + if(mScale == 1.0f) { + return; // nothing to scale + } + + ai_assert( mScale != 0 ); + ai_assert( nullptr != pScene ); + ai_assert( nullptr != pScene->mRootNode ); + + if ( nullptr == pScene ) { + return; + } + + if ( nullptr == pScene->mRootNode ) { + return; + } + + // Process animations and update position transform to new unit system + for( unsigned int animationID = 0; animationID < pScene->mNumAnimations; animationID++ ) + { + aiAnimation* animation = pScene->mAnimations[animationID]; + + for( unsigned int animationChannel = 0; animationChannel < animation->mNumChannels; animationChannel++) + { + aiNodeAnim* anim = animation->mChannels[animationChannel]; + + for( unsigned int posKey = 0; posKey < anim->mNumPositionKeys; posKey++) + { + aiVectorKey& vectorKey = anim->mPositionKeys[posKey]; + vectorKey.mValue *= mScale; + } + } + } + + for( unsigned int meshID = 0; meshID < pScene->mNumMeshes; meshID++) + { + aiMesh *mesh = pScene->mMeshes[meshID]; + + // Reconstruct mesh vertexes to the new unit system + for( unsigned int vertexID = 0; vertexID < mesh->mNumVertices; vertexID++) + { + aiVector3D& vertex = mesh->mVertices[vertexID]; + vertex *= mScale; + } + + + // bone placement / scaling + for( unsigned int boneID = 0; boneID < mesh->mNumBones; boneID++) + { + // Reconstruct matrix by transform rather than by scale + // This prevent scale values being changed which can + // be meaningful in some cases + // like when you want the modeller to see 1:1 compatibility. + aiBone* bone = mesh->mBones[boneID]; + + aiVector3D pos, scale; + aiQuaternion rotation; + + bone->mOffsetMatrix.Decompose( scale, rotation, pos); + + aiMatrix4x4 translation; + aiMatrix4x4::Translation( pos * mScale, translation ); + + aiMatrix4x4 scaling; + aiMatrix4x4::Scaling( aiVector3D(scale), scaling ); + + aiMatrix4x4 RotMatrix = aiMatrix4x4 (rotation.GetMatrix()); + + bone->mOffsetMatrix = translation * RotMatrix * scaling; + } + + + // animation mesh processing + // convert by position rather than scale. + for( unsigned int animMeshID = 0; animMeshID < mesh->mNumAnimMeshes; animMeshID++) + { + aiAnimMesh * animMesh = mesh->mAnimMeshes[animMeshID]; + + for( unsigned int vertexID = 0; vertexID < animMesh->mNumVertices; vertexID++) + { + aiVector3D& vertex = animMesh->mVertices[vertexID]; + vertex *= mScale; + } + } + } + + traverseNodes( pScene->mRootNode ); +} + +void ScaleProcess::traverseNodes( aiNode *node, unsigned int nested_node_id ) { + applyScaling( node ); + + for( size_t i = 0; i < node->mNumChildren; i++) + { + // recurse into the tree until we are done! + traverseNodes( node->mChildren[i], nested_node_id+1 ); + } +} + +void ScaleProcess::applyScaling( aiNode *currentNode ) { + if ( nullptr != currentNode ) { + // Reconstruct matrix by transform rather than by scale + // This prevent scale values being changed which can + // be meaningful in some cases + // like when you want the modeller to + // see 1:1 compatibility. + + aiVector3D pos, scale; + aiQuaternion rotation; + currentNode->mTransformation.Decompose( scale, rotation, pos); + + aiMatrix4x4 translation; + aiMatrix4x4::Translation( pos * mScale, translation ); + + aiMatrix4x4 scaling; + + // note: we do not use mScale here, this is on purpose. + aiMatrix4x4::Scaling( scale, scaling ); + + aiMatrix4x4 RotMatrix = aiMatrix4x4 (rotation.GetMatrix()); + + currentNode->mTransformation = translation * RotMatrix * scaling; + } +} + +} // Namespace Assimp diff --git a/third_party/libassimp/code/ScaleProcess.h b/third_party/libassimp/code/PostProcessing/ScaleProcess.h similarity index 83% rename from third_party/libassimp/code/ScaleProcess.h rename to third_party/libassimp/code/PostProcessing/ScaleProcess.h index 0621220a89..468a216736 100644 --- a/third_party/libassimp/code/ScaleProcess.h +++ b/third_party/libassimp/code/PostProcessing/ScaleProcess.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -39,9 +39,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------- */ -#pragma once +#ifndef SCALE_PROCESS_H_ +#define SCALE_PROCESS_H_ -#include "BaseProcess.h" +#include "Common/BaseProcess.h" struct aiNode; @@ -53,6 +54,11 @@ namespace Assimp { // --------------------------------------------------------------------------- /** ScaleProcess: Class to rescale the whole model. + * Now rescales animations, bones, and blend shapes properly. + * Please note this will not write to 'scale' transform it will rewrite mesh + * and matrixes so that your scale values + * from your model package are preserved, so this is completely intentional + * bugs should be reported as soon as they are found. */ class ASSIMP_API ScaleProcess : public BaseProcess { public: @@ -78,7 +84,7 @@ public: virtual void Execute( aiScene* pScene ); private: - void traverseNodes( aiNode *currentNode ); + void traverseNodes( aiNode *currentNode, unsigned int nested_node_id = 0 ); void applyScaling( aiNode *currentNode ); private: @@ -86,3 +92,6 @@ private: }; } // Namespace Assimp + + +#endif // SCALE_PROCESS_H_ \ No newline at end of file diff --git a/third_party/libassimp/code/SortByPTypeProcess.cpp b/third_party/libassimp/code/PostProcessing/SortByPTypeProcess.cpp similarity index 89% rename from third_party/libassimp/code/SortByPTypeProcess.cpp rename to third_party/libassimp/code/PostProcessing/SortByPTypeProcess.cpp index b67da5b954..be8405a17b 100644 --- a/third_party/libassimp/code/SortByPTypeProcess.cpp +++ b/third_party/libassimp/code/PostProcessing/SortByPTypeProcess.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -57,8 +57,8 @@ using namespace Assimp; // ------------------------------------------------------------------------------------------------ // Constructor to be privately used by Importer SortByPTypeProcess::SortByPTypeProcess() -{ - configRemoveMeshes = 0; +: mConfigRemoveMeshes( 0 ) { + // empty } // ------------------------------------------------------------------------------------------------ @@ -78,7 +78,7 @@ bool SortByPTypeProcess::IsActive( unsigned int pFlags) const // ------------------------------------------------------------------------------------------------ void SortByPTypeProcess::SetupProperties(const Importer* pImp) { - configRemoveMeshes = pImp->GetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE,0); + mConfigRemoveMeshes = pImp->GetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE,0); } // ------------------------------------------------------------------------------------------------ @@ -172,7 +172,7 @@ void SortByPTypeProcess::Execute( aiScene* pScene) { } if (1 == num) { - if (!(configRemoveMeshes & mesh->mPrimitiveTypes)) { + if (!(mConfigRemoveMeshes & mesh->mPrimitiveTypes)) { *meshIdx = static_cast( outMeshes.size() ); outMeshes.push_back(mesh); } else { @@ -206,7 +206,7 @@ void SortByPTypeProcess::Execute( aiScene* pScene) { VertexWeightTable* avw = ComputeVertexBoneWeightTable(mesh); for (unsigned int real = 0; real < 4; ++real,++meshIdx) { - if ( !aiNumPerPType[real] || configRemoveMeshes & (1u << real)) + if ( !aiNumPerPType[real] || mConfigRemoveMeshes & (1u << real)) { continue; } @@ -228,36 +228,37 @@ void SortByPTypeProcess::Execute( aiScene* pScene) { out->mNumVertices = (3 == real ? numPolyVerts : out->mNumFaces * (real+1)); - aiVector3D *vert(NULL), *nor(NULL), *tan(NULL), *bit(NULL); + aiVector3D *vert(nullptr), *nor(nullptr), *tan(nullptr), *bit(nullptr); aiVector3D *uv [AI_MAX_NUMBER_OF_TEXTURECOORDS]; aiColor4D *cols [AI_MAX_NUMBER_OF_COLOR_SETS]; - if (mesh->mVertices) + if (mesh->mVertices) { vert = out->mVertices = new aiVector3D[out->mNumVertices]; + } - if (mesh->mNormals) - nor = out->mNormals = new aiVector3D[out->mNumVertices]; + if (mesh->mNormals) { + nor = out->mNormals = new aiVector3D[out->mNumVertices]; + } - if (mesh->mTangents) - { + if (mesh->mTangents) { tan = out->mTangents = new aiVector3D[out->mNumVertices]; bit = out->mBitangents = new aiVector3D[out->mNumVertices]; } - for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS;++i) - { - if (mesh->mTextureCoords[i]) - uv[i] = out->mTextureCoords[i] = new aiVector3D[out->mNumVertices]; - else uv[i] = NULL; + for (unsigned int j = 0; j < AI_MAX_NUMBER_OF_TEXTURECOORDS;++j) { + uv[j] = nullptr; + if (mesh->mTextureCoords[j]) { + uv[j] = out->mTextureCoords[j] = new aiVector3D[out->mNumVertices]; + } - out->mNumUVComponents[i] = mesh->mNumUVComponents[i]; + out->mNumUVComponents[j] = mesh->mNumUVComponents[j]; } - for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS;++i) - { - if (mesh->mColors[i]) - cols[i] = out->mColors[i] = new aiColor4D[out->mNumVertices]; - else cols[i] = NULL; + for (unsigned int j = 0; j < AI_MAX_NUMBER_OF_COLOR_SETS;++j) { + cols[j] = nullptr; + if (mesh->mColors[j]) { + cols[j] = out->mColors[j] = new aiColor4D[out->mNumVertices]; + } } typedef std::vector< aiVertexWeight > TempBoneInfo; @@ -323,7 +324,7 @@ void SortByPTypeProcess::Execute( aiScene* pScene) { in.mIndices[q] = outIdx++; } - in.mIndices = NULL; + in.mIndices = nullptr; ++outFaces; } ai_assert(outFaces == out->mFaces + out->mNumFaces); @@ -391,10 +392,10 @@ void SortByPTypeProcess::Execute( aiScene* pScene) { { char buffer[1024]; ::ai_snprintf(buffer,1024,"Points: %u%s, Lines: %u%s, Triangles: %u%s, Polygons: %u%s (Meshes, X = removed)", - aiNumMeshesPerPType[0], ((configRemoveMeshes & aiPrimitiveType_POINT) ? "X" : ""), - aiNumMeshesPerPType[1], ((configRemoveMeshes & aiPrimitiveType_LINE) ? "X" : ""), - aiNumMeshesPerPType[2], ((configRemoveMeshes & aiPrimitiveType_TRIANGLE) ? "X" : ""), - aiNumMeshesPerPType[3], ((configRemoveMeshes & aiPrimitiveType_POLYGON) ? "X" : "")); + aiNumMeshesPerPType[0], ((mConfigRemoveMeshes & aiPrimitiveType_POINT) ? "X" : ""), + aiNumMeshesPerPType[1], ((mConfigRemoveMeshes & aiPrimitiveType_LINE) ? "X" : ""), + aiNumMeshesPerPType[2], ((mConfigRemoveMeshes & aiPrimitiveType_TRIANGLE) ? "X" : ""), + aiNumMeshesPerPType[3], ((mConfigRemoveMeshes & aiPrimitiveType_POLYGON) ? "X" : "")); ASSIMP_LOG_INFO(buffer); ASSIMP_LOG_DEBUG("SortByPTypeProcess finished"); } diff --git a/third_party/libassimp/code/SortByPTypeProcess.h b/third_party/libassimp/code/PostProcessing/SortByPTypeProcess.h similarity index 94% rename from third_party/libassimp/code/SortByPTypeProcess.h rename to third_party/libassimp/code/PostProcessing/SortByPTypeProcess.h index 27bfa21554..1d7ccfc152 100644 --- a/third_party/libassimp/code/SortByPTypeProcess.h +++ b/third_party/libassimp/code/PostProcessing/SortByPTypeProcess.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -45,10 +45,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_SORTBYPTYPEPROCESS_H_INC #define AI_SORTBYPTYPEPROCESS_H_INC -#include "BaseProcess.h" +#include "Common/BaseProcess.h" #include class SortByPTypeProcessTest; + namespace Assimp { @@ -57,14 +58,11 @@ namespace Assimp { * A mesh with 5 lines, 3 points and 145 triangles would be split in 3 * submeshes. */ -class ASSIMP_API SortByPTypeProcess : public BaseProcess -{ +class ASSIMP_API SortByPTypeProcess : public BaseProcess { public: - SortByPTypeProcess(); ~SortByPTypeProcess(); -public: // ------------------------------------------------------------------- bool IsActive( unsigned int pFlags) const; @@ -75,8 +73,7 @@ public: void SetupProperties(const Importer* pImp); private: - - int configRemoveMeshes; + int mConfigRemoveMeshes; }; diff --git a/third_party/libassimp/code/SplitLargeMeshes.cpp b/third_party/libassimp/code/PostProcessing/SplitLargeMeshes.cpp similarity index 99% rename from third_party/libassimp/code/SplitLargeMeshes.cpp rename to third_party/libassimp/code/PostProcessing/SplitLargeMeshes.cpp index 5cd3afe48a..1797b28d5a 100644 --- a/third_party/libassimp/code/SplitLargeMeshes.cpp +++ b/third_party/libassimp/code/PostProcessing/SplitLargeMeshes.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/SplitLargeMeshes.h b/third_party/libassimp/code/PostProcessing/SplitLargeMeshes.h similarity index 98% rename from third_party/libassimp/code/SplitLargeMeshes.h rename to third_party/libassimp/code/PostProcessing/SplitLargeMeshes.h index 7a977ff07c..3f90576ea9 100644 --- a/third_party/libassimp/code/SplitLargeMeshes.h +++ b/third_party/libassimp/code/PostProcessing/SplitLargeMeshes.h @@ -2,8 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team - +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -40,21 +39,21 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------- */ -/** @file Defines a post processing step to split large meshes into submeshes +/** @file Defines a post processing step to split large meshes into sub-meshes */ #ifndef AI_SPLITLARGEMESHES_H_INC #define AI_SPLITLARGEMESHES_H_INC #include -#include "BaseProcess.h" +#include "Common/BaseProcess.h" #include #include +// Forward declarations class SplitLargeMeshesTest; -namespace Assimp -{ +namespace Assimp { class SplitLargeMeshesProcess_Triangle; class SplitLargeMeshesProcess_Vertex; diff --git a/third_party/libassimp/code/TextureTransform.cpp b/third_party/libassimp/code/PostProcessing/TextureTransform.cpp similarity index 99% rename from third_party/libassimp/code/TextureTransform.cpp rename to third_party/libassimp/code/PostProcessing/TextureTransform.cpp index c7adbe7a9d..8ae2ba7218 100644 --- a/third_party/libassimp/code/TextureTransform.cpp +++ b/third_party/libassimp/code/PostProcessing/TextureTransform.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/TextureTransform.h b/third_party/libassimp/code/PostProcessing/TextureTransform.h similarity index 98% rename from third_party/libassimp/code/TextureTransform.h rename to third_party/libassimp/code/PostProcessing/TextureTransform.h index 99d5acf1e8..2a5d623d7f 100644 --- a/third_party/libassimp/code/TextureTransform.h +++ b/third_party/libassimp/code/PostProcessing/TextureTransform.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -45,7 +45,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define AI_TEXTURE_TRANSFORM_H_INCLUDED #include -#include "BaseProcess.h" +#include "Common/BaseProcess.h" #include #include diff --git a/third_party/libassimp/code/TriangulateProcess.cpp b/third_party/libassimp/code/PostProcessing/TriangulateProcess.cpp similarity index 99% rename from third_party/libassimp/code/TriangulateProcess.cpp rename to third_party/libassimp/code/PostProcessing/TriangulateProcess.cpp index b2ea46ef7e..1040836bbe 100644 --- a/third_party/libassimp/code/TriangulateProcess.cpp +++ b/third_party/libassimp/code/PostProcessing/TriangulateProcess.cpp @@ -3,9 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team - - +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -60,9 +58,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * a file */ #ifndef ASSIMP_BUILD_NO_TRIANGULATE_PROCESS -#include "TriangulateProcess.h" -#include "ProcessHelper.h" -#include "PolyTools.h" + +#include "PostProcessing/TriangulateProcess.h" +#include "PostProcessing/ProcessHelper.h" +#include "Common/PolyTools.h" + #include //#define AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING diff --git a/third_party/libassimp/code/TriangulateProcess.h b/third_party/libassimp/code/PostProcessing/TriangulateProcess.h similarity index 95% rename from third_party/libassimp/code/TriangulateProcess.h rename to third_party/libassimp/code/PostProcessing/TriangulateProcess.h index e6300085da..916b5103dd 100644 --- a/third_party/libassimp/code/TriangulateProcess.h +++ b/third_party/libassimp/code/PostProcessing/TriangulateProcess.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -46,7 +46,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_TRIANGULATEPROCESS_H_INC #define AI_TRIANGULATEPROCESS_H_INC -#include "BaseProcess.h" +#include "Common/BaseProcess.h" struct aiMesh; @@ -59,14 +59,11 @@ namespace Assimp { * into triangles. You usually want this to happen because the graphics cards * need their data as triangles. */ -class ASSIMP_API TriangulateProcess : public BaseProcess -{ +class ASSIMP_API TriangulateProcess : public BaseProcess { public: - TriangulateProcess(); ~TriangulateProcess(); -public: // ------------------------------------------------------------------- /** Returns whether the processing step is present in the given flag field. * @param pFlags The processing flags the importer was called with. A bitwise @@ -82,7 +79,6 @@ public: */ void Execute( aiScene* pScene); -public: // ------------------------------------------------------------------- /** Triangulates the given mesh. * @param pMesh The mesh to triangulate. diff --git a/third_party/libassimp/code/ValidateDataStructure.cpp b/third_party/libassimp/code/PostProcessing/ValidateDataStructure.cpp similarity index 91% rename from third_party/libassimp/code/ValidateDataStructure.cpp rename to third_party/libassimp/code/PostProcessing/ValidateDataStructure.cpp index 931c528220..501f7a9b2b 100644 --- a/third_party/libassimp/code/ValidateDataStructure.cpp +++ b/third_party/libassimp/code/PostProcessing/ValidateDataStructure.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -46,8 +46,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * the data structure returned by Assimp. */ - - // internal headers #include "ValidateDataStructure.h" #include @@ -110,8 +108,8 @@ void ValidateDSProcess::ReportWarning(const char* msg,...) } // ------------------------------------------------------------------------------------------------ -inline int HasNameMatch(const aiString& in, aiNode* node) -{ +inline +int HasNameMatch(const aiString& in, aiNode* node) { int result = (node->mName == in ? 1 : 0 ); for (unsigned int i = 0; i < node->mNumChildren;++i) { result += HasNameMatch(in,node->mChildren[i]); @@ -121,9 +119,8 @@ inline int HasNameMatch(const aiString& in, aiNode* node) // ------------------------------------------------------------------------------------------------ template -inline void ValidateDSProcess::DoValidation(T** parray, unsigned int size, - const char* firstName, const char* secondName) -{ +inline +void ValidateDSProcess::DoValidation(T** parray, unsigned int size, const char* firstName, const char* secondName) { // validate all entries if (size) { @@ -160,7 +157,7 @@ inline void ValidateDSProcess::DoValidationEx(T** parray, unsigned int size, { if (!parray[i]) { - ReportError("aiScene::%s[%i] is NULL (aiScene::%s is %i)", + ReportError("aiScene::%s[%u] is NULL (aiScene::%s is %u)", firstName,i,secondName,size); } Validate(parray[i]); @@ -170,8 +167,8 @@ inline void ValidateDSProcess::DoValidationEx(T** parray, unsigned int size, { if (parray[i]->mName == parray[a]->mName) { - this->ReportError("aiScene::%s[%i] has the same name as " - "aiScene::%s[%i]",firstName, i,secondName, a); + ReportError("aiScene::%s[%u] has the same name as " + "aiScene::%s[%u]",firstName, i,secondName, a); } } } @@ -180,32 +177,30 @@ inline void ValidateDSProcess::DoValidationEx(T** parray, unsigned int size, // ------------------------------------------------------------------------------------------------ template -inline void ValidateDSProcess::DoValidationWithNameCheck(T** array, - unsigned int size, const char* firstName, - const char* secondName) -{ +inline +void ValidateDSProcess::DoValidationWithNameCheck(T** array, unsigned int size, const char* firstName, + const char* secondName) { // validate all entries DoValidationEx(array,size,firstName,secondName); - for (unsigned int i = 0; i < size;++i) - { + for (unsigned int i = 0; i < size;++i) { int res = HasNameMatch(array[i]->mName,mScene->mRootNode); - if (!res) { + if (0 == res) { + const std::string name = static_cast(array[i]->mName.data); ReportError("aiScene::%s[%i] has no corresponding node in the scene graph (%s)", - firstName,i,array[i]->mName.data); - } - else if (1 != res) { + firstName,i, name.c_str()); + } else if (1 != res) { + const std::string name = static_cast(array[i]->mName.data); ReportError("aiScene::%s[%i]: there are more than one nodes with %s as name", - firstName,i,array[i]->mName.data); + firstName,i, name.c_str()); } } } // ------------------------------------------------------------------------------------------------ // Executes the post processing step on the given imported data. -void ValidateDSProcess::Execute( aiScene* pScene) -{ - this->mScene = pScene; +void ValidateDSProcess::Execute( aiScene* pScene) { + mScene = pScene; ASSIMP_LOG_DEBUG("ValidateDataStructureProcess begin"); // validate the node graph of the scene @@ -332,6 +327,7 @@ void ValidateDSProcess::Validate( const aiMesh* pMesh) { case 0: ReportError("aiMesh::mFaces[%i].mNumIndices is 0",i); + break; case 1: if (0 == (pMesh->mPrimitiveTypes & aiPrimitiveType_POINT)) { @@ -424,7 +420,9 @@ void ValidateDSProcess::Validate( const aiMesh* pMesh) if (!abRefList[i])b = true; } abRefList.clear(); - if (b)ReportWarning("There are unreferenced vertices"); + if (b) { + ReportWarning("There are unreferenced vertices"); + } // texture channel 2 may not be set if channel 1 is zero ... { @@ -515,13 +513,11 @@ void ValidateDSProcess::Validate( const aiMesh* pMesh) } // ------------------------------------------------------------------------------------------------ -void ValidateDSProcess::Validate( const aiMesh* pMesh, - const aiBone* pBone,float* afSum) -{ +void ValidateDSProcess::Validate( const aiMesh* pMesh, const aiBone* pBone,float* afSum) { this->Validate(&pBone->mName); if (!pBone->mNumWeights) { - ReportError("aiBone::mNumWeights is zero"); + //ReportError("aiBone::mNumWeights is zero"); } // check whether all vertices affected by this bone are valid @@ -559,10 +555,9 @@ void ValidateDSProcess::Validate( const aiAnimation* pAnimation) Validate(pAnimation, pAnimation->mChannels[i]); } } - else ReportError("aiAnimation::mNumChannels is 0. At least one node animation channel must be there."); - - // Animation duration is allowed to be zero in cases where the anim contains only a single key frame. - // if (!pAnimation->mDuration)this->ReportError("aiAnimation::mDuration is zero"); + else { + ReportError("aiAnimation::mNumChannels is 0. At least one node animation channel must be there."); + } } // ------------------------------------------------------------------------------------------------ @@ -579,15 +574,16 @@ void ValidateDSProcess::SearchForInvalidTextures(const aiMaterial* pMaterial, int iNumIndices = 0; int iIndex = -1; - for (unsigned int i = 0; i < pMaterial->mNumProperties;++i) - { - aiMaterialProperty* prop = pMaterial->mProperties[i]; - if (!::strcmp(prop->mKey.data,"$tex.file") && prop->mSemantic == type) { + for (unsigned int i = 0; i < pMaterial->mNumProperties;++i) { + aiMaterialProperty* prop = pMaterial->mProperties[ i ]; + ai_assert(nullptr != prop); + if ( !::strcmp(prop->mKey.data,"$tex.file") && prop->mSemantic == static_cast(type)) { iIndex = std::max(iIndex, (int) prop->mIndex); ++iNumIndices; - if (aiPTI_String != prop->mType) - ReportError("Material property %s is expected to be a string",prop->mKey.data); + if (aiPTI_String != prop->mType) { + ReportError("Material property %s is expected to be a string", prop->mKey.data); + } } } if (iIndex +1 != iNumIndices) { @@ -699,7 +695,7 @@ void ValidateDSProcess::Validate( const aiMaterial* pMaterial) if (prop->mDataLength < 5 || prop->mDataLength < 4 + (*reinterpret_cast(prop->mData)) + 1) { ReportError("aiMaterial::mProperties[%i].mDataLength is " "too small to contain a string (%i, needed: %i)", - i,prop->mDataLength,sizeof(aiString)); + i,prop->mDataLength,static_cast(sizeof(aiString))); } if(prop->mData[prop->mDataLength-1]) { ReportError("Missing null-terminator in string material property"); @@ -710,14 +706,14 @@ void ValidateDSProcess::Validate( const aiMaterial* pMaterial) if (prop->mDataLength < sizeof(float)) { ReportError("aiMaterial::mProperties[%i].mDataLength is " "too small to contain a float (%i, needed: %i)", - i,prop->mDataLength,sizeof(float)); + i,prop->mDataLength, static_cast(sizeof(float))); } } else if (aiPTI_Integer == prop->mType) { if (prop->mDataLength < sizeof(int)) { ReportError("aiMaterial::mProperties[%i].mDataLength is " "too small to contain an integer (%i, needed: %i)", - i,prop->mDataLength,sizeof(int)); + i,prop->mDataLength, static_cast(sizeof(int))); } } // TODO: check whether there is a key with an unknown name ... @@ -742,8 +738,9 @@ void ValidateDSProcess::Validate( const aiMaterial* pMaterial) "AI_MATKEY_SHININESS_STRENGTH key is 0.0"); } break; - default: ; - }; + default: + break; + } } if (AI_SUCCESS == aiGetMaterialFloat( pMaterial,AI_MATKEY_OPACITY,&fTemp) && (!fTemp || fTemp > 1.01)) { @@ -775,8 +772,10 @@ void ValidateDSProcess::Validate( const aiTexture* pTexture) } if (pTexture->mHeight) { - if (!pTexture->mWidth)ReportError("aiTexture::mWidth is zero " - "(aiTexture::mHeight is %i, uncompressed texture)",pTexture->mHeight); + if (!pTexture->mWidth){ + ReportError("aiTexture::mWidth is zero (aiTexture::mHeight is %i, uncompressed texture)", + pTexture->mHeight); + } } else { @@ -807,15 +806,15 @@ void ValidateDSProcess::Validate( const aiAnimation* pAnimation, { Validate(&pNodeAnim->mNodeName); - if (!pNodeAnim->mNumPositionKeys && !pNodeAnim->mScalingKeys && !pNodeAnim->mNumRotationKeys) + if (!pNodeAnim->mNumPositionKeys && !pNodeAnim->mScalingKeys && !pNodeAnim->mNumRotationKeys) { ReportError("Empty node animation channel"); - + } // otherwise check whether one of the keys exceeds the total duration of the animation if (pNodeAnim->mNumPositionKeys) { if (!pNodeAnim->mPositionKeys) { - this->ReportError("aiNodeAnim::mPositionKeys is NULL (aiNodeAnim::mNumPositionKeys is %i)", + ReportError("aiNodeAnim::mPositionKeys is NULL (aiNodeAnim::mNumPositionKeys is %i)", pNodeAnim->mNumPositionKeys); } double dLast = -10e10; @@ -846,7 +845,7 @@ void ValidateDSProcess::Validate( const aiAnimation* pAnimation, { if (!pNodeAnim->mRotationKeys) { - this->ReportError("aiNodeAnim::mRotationKeys is NULL (aiNodeAnim::mNumRotationKeys is %i)", + ReportError("aiNodeAnim::mRotationKeys is NULL (aiNodeAnim::mNumRotationKeys is %i)", pNodeAnim->mNumRotationKeys); } double dLast = -10e10; @@ -907,19 +906,23 @@ void ValidateDSProcess::Validate( const aiAnimation* pAnimation, // ------------------------------------------------------------------------------------------------ void ValidateDSProcess::Validate( const aiNode* pNode) { - if (!pNode)ReportError("A node of the scenegraph is NULL"); - if (pNode != mScene->mRootNode && !pNode->mParent) - this->ReportError("A node has no valid parent (aiNode::mParent is NULL)"); - + if (!pNode) { + ReportError("A node of the scenegraph is NULL"); + } + // Validate node name string first so that it's safe to use in below expressions this->Validate(&pNode->mName); + const char* nodeName = (&pNode->mName)->C_Str(); + if (pNode != mScene->mRootNode && !pNode->mParent){ + ReportError("Non-root node %s lacks a valid parent (aiNode::mParent is NULL) ", nodeName); + } // validate all meshes if (pNode->mNumMeshes) { if (!pNode->mMeshes) { - ReportError("aiNode::mMeshes is NULL (aiNode::mNumMeshes is %i)", - pNode->mNumMeshes); + ReportError("aiNode::mMeshes is NULL for node %s (aiNode::mNumMeshes is %i)", + nodeName, pNode->mNumMeshes); } std::vector abHadMesh; abHadMesh.resize(mScene->mNumMeshes,false); @@ -927,13 +930,13 @@ void ValidateDSProcess::Validate( const aiNode* pNode) { if (pNode->mMeshes[i] >= mScene->mNumMeshes) { - ReportError("aiNode::mMeshes[%i] is out of range (maximum is %i)", - pNode->mMeshes[i],mScene->mNumMeshes-1); + ReportError("aiNode::mMeshes[%i] is out of range for node %s (maximum is %i)", + pNode->mMeshes[i], nodeName, mScene->mNumMeshes-1); } if (abHadMesh[pNode->mMeshes[i]]) { - ReportError("aiNode::mMeshes[%i] is already referenced by this node (value: %i)", - i,pNode->mMeshes[i]); + ReportError("aiNode::mMeshes[%i] is already referenced by this node %s (value: %i)", + i, nodeName, pNode->mMeshes[i]); } abHadMesh[pNode->mMeshes[i]] = true; } @@ -941,8 +944,8 @@ void ValidateDSProcess::Validate( const aiNode* pNode) if (pNode->mNumChildren) { if (!pNode->mChildren) { - ReportError("aiNode::mChildren is NULL (aiNode::mNumChildren is %i)", - pNode->mNumChildren); + ReportError("aiNode::mChildren is NULL for node %s (aiNode::mNumChildren is %i)", + nodeName, pNode->mNumChildren); } for (unsigned int i = 0; i < pNode->mNumChildren;++i) { Validate(pNode->mChildren[i]); @@ -955,7 +958,7 @@ void ValidateDSProcess::Validate( const aiString* pString) { if (pString->length > MAXLEN) { - this->ReportError("aiString::length is too large (%i, maximum is %i)", + ReportError("aiString::length is too large (%u, maximum is %lu)", pString->length,MAXLEN); } const char* sz = pString->data; @@ -963,12 +966,14 @@ void ValidateDSProcess::Validate( const aiString* pString) { if ('\0' == *sz) { - if (pString->length != (unsigned int)(sz-pString->data)) + if (pString->length != (unsigned int)(sz-pString->data)) { ReportError("aiString::data is invalid: the terminal zero is at a wrong offset"); + } break; } - else if (sz >= &pString->data[MAXLEN]) + else if (sz >= &pString->data[MAXLEN]) { ReportError("aiString::data is invalid. There is no terminal character"); + } ++sz; } } diff --git a/third_party/libassimp/code/ValidateDataStructure.h b/third_party/libassimp/code/PostProcessing/ValidateDataStructure.h similarity index 98% rename from third_party/libassimp/code/ValidateDataStructure.h rename to third_party/libassimp/code/PostProcessing/ValidateDataStructure.h index 4e1636bfa1..0b891ef414 100644 --- a/third_party/libassimp/code/ValidateDataStructure.h +++ b/third_party/libassimp/code/PostProcessing/ValidateDataStructure.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -48,7 +48,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include "BaseProcess.h" + +#include "Common/BaseProcess.h" struct aiBone; struct aiMesh; diff --git a/third_party/libassimp/code/Q3BSPFileData.h b/third_party/libassimp/code/Q3BSP/Q3BSPFileData.h similarity index 99% rename from third_party/libassimp/code/Q3BSPFileData.h rename to third_party/libassimp/code/Q3BSP/Q3BSPFileData.h index d814837c2c..4e05bebf19 100644 --- a/third_party/libassimp/code/Q3BSPFileData.h +++ b/third_party/libassimp/code/Q3BSP/Q3BSPFileData.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/Q3BSPFileImporter.cpp b/third_party/libassimp/code/Q3BSP/Q3BSPFileImporter.cpp similarity index 97% rename from third_party/libassimp/code/Q3BSPFileImporter.cpp rename to third_party/libassimp/code/Q3BSP/Q3BSPFileImporter.cpp index 58fbef985f..4add00a07f 100644 --- a/third_party/libassimp/code/Q3BSPFileImporter.cpp +++ b/third_party/libassimp/code/Q3BSP/Q3BSPFileImporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -43,7 +43,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_Q3BSP_IMPORTER #include "Q3BSPFileImporter.h" -#include "Q3BSPZipArchive.h" #include "Q3BSPFileParser.h" #include "Q3BSPFileData.h" @@ -60,6 +59,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include +#include #include #include #include @@ -181,7 +181,7 @@ const aiImporterDesc* Q3BSPFileImporter::GetInfo () const { // ------------------------------------------------------------------------------------------------ // Import method. void Q3BSPFileImporter::InternReadFile(const std::string &rFile, aiScene* scene, IOSystem* ioHandler) { - Q3BSPZipArchive Archive( ioHandler, rFile ); + ZipArchiveIOSystem Archive( ioHandler, rFile ); if ( !Archive.isOpen() ) { throw DeadlyImportError( "Failed to open file " + rFile + "." ); } @@ -223,10 +223,10 @@ void Q3BSPFileImporter::separateMapName( const std::string &importName, std::str // ------------------------------------------------------------------------------------------------ // Returns the first map in the map archive. -bool Q3BSPFileImporter::findFirstMapInArchive( Q3BSPZipArchive &bspArchive, std::string &mapName ) { +bool Q3BSPFileImporter::findFirstMapInArchive(ZipArchiveIOSystem &bspArchive, std::string &mapName ) { mapName = ""; std::vector fileList; - bspArchive.getFileList( fileList ); + bspArchive.getFileListExtension( fileList, "bsp" ); if (fileList.empty()) { return false; } @@ -249,7 +249,7 @@ bool Q3BSPFileImporter::findFirstMapInArchive( Q3BSPZipArchive &bspArchive, std: // ------------------------------------------------------------------------------------------------ // Creates the assimp specific data. void Q3BSPFileImporter::CreateDataFromImport( const Q3BSP::Q3BSPModel *pModel, aiScene* pScene, - Q3BSPZipArchive *pArchive ) { + ZipArchiveIOSystem *pArchive ) { if (nullptr == pModel || nullptr == pScene) { return; } @@ -400,6 +400,7 @@ void Q3BSPFileImporter::createTriangleTopology( const Q3BSP::Q3BSPModel *pModel, if (nullptr != m_pCurrentFace) { m_pCurrentFace->mNumIndices = 3; m_pCurrentFace->mIndices = new unsigned int[3]; + m_pCurrentFace->mIndices[ idx ] = vertIdx; } } @@ -409,9 +410,7 @@ void Q3BSPFileImporter::createTriangleTopology( const Q3BSP::Q3BSPModel *pModel, pMesh->mTextureCoords[ 0 ][ vertIdx ].Set( pVertex->vTexCoord.x, pVertex->vTexCoord.y, 0.0f ); pMesh->mTextureCoords[ 1 ][ vertIdx ].Set( pVertex->vLightmap.x, pVertex->vLightmap.y, 0.0f ); - m_pCurrentFace->mIndices[ idx ] = vertIdx; vertIdx++; - idx++; } } @@ -419,7 +418,7 @@ void Q3BSPFileImporter::createTriangleTopology( const Q3BSP::Q3BSPModel *pModel, // ------------------------------------------------------------------------------------------------ // Creates all referenced materials. void Q3BSPFileImporter::createMaterials( const Q3BSP::Q3BSPModel *pModel, aiScene* pScene, - Q3BSPZipArchive *pArchive ) { + ZipArchiveIOSystem *pArchive ) { if ( m_MaterialLookupMap.empty() ) { return; } @@ -565,7 +564,7 @@ aiFace *Q3BSPFileImporter::getNextFace( aiMesh *mesh, unsigned int &faceIdx ) { // ------------------------------------------------------------------------------------------------ // Imports a texture file. bool Q3BSPFileImporter::importTextureFromArchive( const Q3BSP::Q3BSPModel *model, - Q3BSP::Q3BSPZipArchive *archive, aiScene*, + ZipArchiveIOSystem *archive, aiScene*, aiMaterial *pMatHelper, int textureId ) { if (nullptr == archive || nullptr == pMatHelper ) { return false; @@ -670,7 +669,7 @@ bool Q3BSPFileImporter::importLightmap( const Q3BSP::Q3BSPModel *pModel, aiScene // ------------------------------------------------------------------------------------------------ // Will search for a supported extension. -bool Q3BSPFileImporter::expandFile( Q3BSP::Q3BSPZipArchive *pArchive, const std::string &rFilename, +bool Q3BSPFileImporter::expandFile(ZipArchiveIOSystem *pArchive, const std::string &rFilename, const std::vector &rExtList, std::string &rFile, std::string &rExt ) { diff --git a/third_party/libassimp/code/Q3BSPFileImporter.h b/third_party/libassimp/code/Q3BSP/Q3BSPFileImporter.h similarity index 91% rename from third_party/libassimp/code/Q3BSPFileImporter.h rename to third_party/libassimp/code/Q3BSP/Q3BSPFileImporter.h index 5f3e311574..ee21fa48e6 100644 --- a/third_party/libassimp/code/Q3BSPFileImporter.h +++ b/third_party/libassimp/code/Q3BSP/Q3BSPFileImporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -54,9 +54,9 @@ struct aiMaterial; struct aiTexture; namespace Assimp { + class ZipArchiveIOSystem; namespace Q3BSP { - class Q3BSPZipArchive; struct Q3BSPModel; struct sQ3BSPFace; } @@ -85,24 +85,24 @@ protected: const aiImporterDesc* GetInfo () const; void InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler); void separateMapName( const std::string &rImportName, std::string &rArchiveName, std::string &rMapName ); - bool findFirstMapInArchive( Q3BSP::Q3BSPZipArchive &rArchive, std::string &rMapName ); - void CreateDataFromImport( const Q3BSP::Q3BSPModel *pModel, aiScene* pScene, Q3BSP::Q3BSPZipArchive *pArchive ); + bool findFirstMapInArchive(ZipArchiveIOSystem &rArchive, std::string &rMapName ); + void CreateDataFromImport( const Q3BSP::Q3BSPModel *pModel, aiScene* pScene, ZipArchiveIOSystem *pArchive ); void CreateNodes( const Q3BSP::Q3BSPModel *pModel, aiScene* pScene, aiNode *pParent ); aiNode *CreateTopology( const Q3BSP::Q3BSPModel *pModel, unsigned int materialIdx, std::vector &rArray, aiMesh **pMesh ); void createTriangleTopology( const Q3BSP::Q3BSPModel *pModel, Q3BSP::sQ3BSPFace *pQ3BSPFace, aiMesh* pMesh, unsigned int &rFaceIdx, unsigned int &rVertIdx ); - void createMaterials( const Q3BSP::Q3BSPModel *pModel, aiScene* pScene, Q3BSP::Q3BSPZipArchive *pArchive ); + void createMaterials( const Q3BSP::Q3BSPModel *pModel, aiScene* pScene, ZipArchiveIOSystem *pArchive ); size_t countData( const std::vector &rArray ) const; size_t countFaces( const std::vector &rArray ) const; size_t countTriangles( const std::vector &rArray ) const; void createMaterialMap( const Q3BSP::Q3BSPModel *pModel); aiFace *getNextFace( aiMesh *pMesh, unsigned int &rFaceIdx ); - bool importTextureFromArchive( const Q3BSP::Q3BSPModel *pModel, Q3BSP::Q3BSPZipArchive *pArchive, aiScene* pScene, + bool importTextureFromArchive( const Q3BSP::Q3BSPModel *pModel, ZipArchiveIOSystem *pArchive, aiScene* pScene, aiMaterial *pMatHelper, int textureId ); bool importLightmap( const Q3BSP::Q3BSPModel *pModel, aiScene* pScene, aiMaterial *pMatHelper, int lightmapId ); bool importEntities( const Q3BSP::Q3BSPModel *pModel, aiScene* pScene ); - bool expandFile( Q3BSP::Q3BSPZipArchive *pArchive, const std::string &rFilename, const std::vector &rExtList, + bool expandFile(ZipArchiveIOSystem *pArchive, const std::string &rFilename, const std::vector &rExtList, std::string &rFile, std::string &rExt ); private: diff --git a/third_party/libassimp/code/Q3BSPFileParser.cpp b/third_party/libassimp/code/Q3BSP/Q3BSPFileParser.cpp similarity index 97% rename from third_party/libassimp/code/Q3BSPFileParser.cpp rename to third_party/libassimp/code/Q3BSP/Q3BSPFileParser.cpp index f7038adebd..bed2efe53b 100644 --- a/third_party/libassimp/code/Q3BSPFileParser.cpp +++ b/third_party/libassimp/code/Q3BSP/Q3BSPFileParser.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -45,9 +45,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "Q3BSPFileParser.h" #include "Q3BSPFileData.h" -#include "Q3BSPZipArchive.h" #include #include +#include #include namespace Assimp { @@ -55,7 +55,7 @@ namespace Assimp { using namespace Q3BSP; // ------------------------------------------------------------------------------------------------ -Q3BSPFileParser::Q3BSPFileParser( const std::string &mapName, Q3BSPZipArchive *pZipArchive ) : +Q3BSPFileParser::Q3BSPFileParser( const std::string &mapName, ZipArchiveIOSystem *pZipArchive ) : m_sOffset( 0 ), m_Data(), m_pModel(nullptr), @@ -101,6 +101,7 @@ bool Q3BSPFileParser::readData( const std::string &rMapName ) { const size_t readSize = pMapFile->Read( &m_Data[0], sizeof( char ), size ); if ( readSize != size ) { m_Data.clear(); + m_pZipArchive->Close(pMapFile); return false; } m_pZipArchive->Close( pMapFile ); diff --git a/third_party/libassimp/code/Q3BSPFileParser.h b/third_party/libassimp/code/Q3BSP/Q3BSPFileParser.h similarity index 91% rename from third_party/libassimp/code/Q3BSPFileParser.h rename to third_party/libassimp/code/Q3BSP/Q3BSPFileParser.h index 747d1d4944..fd73f5e10f 100644 --- a/third_party/libassimp/code/Q3BSPFileParser.h +++ b/third_party/libassimp/code/Q3BSP/Q3BSPFileParser.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -48,13 +48,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. namespace Assimp { + class ZipArchiveIOSystem; + namespace Q3BSP { - -class Q3BSPZipArchive; -struct Q3BSPModel; -class ZipFile; - + struct Q3BSPModel; + class ZipFile; } // ------------------------------------------------------------------- @@ -62,7 +61,7 @@ class ZipFile; class Q3BSPFileParser { public: - Q3BSPFileParser( const std::string &rMapName, Q3BSP::Q3BSPZipArchive *pZipArchive ); + Q3BSPFileParser( const std::string &rMapName, ZipArchiveIOSystem *pZipArchive ); ~Q3BSPFileParser(); Q3BSP::Q3BSPModel *getModel() const; @@ -83,7 +82,7 @@ private: size_t m_sOffset; std::vector m_Data; Q3BSP::Q3BSPModel *m_pModel; - Q3BSP::Q3BSPZipArchive *m_pZipArchive; + ZipArchiveIOSystem *m_pZipArchive; }; } // Namespace Assimp diff --git a/third_party/libassimp/code/Q3BSPZipArchive.cpp b/third_party/libassimp/code/Q3BSPZipArchive.cpp deleted file mode 100644 index 3e1087b9a2..0000000000 --- a/third_party/libassimp/code/Q3BSPZipArchive.cpp +++ /dev/null @@ -1,315 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2018, 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. - ----------------------------------------------------------------------- -*/ - -#ifndef ASSIMP_BUILD_NO_Q3BSP_IMPORTER - -#include "Q3BSPZipArchive.h" -#include -#include -#include - -namespace Assimp { -namespace Q3BSP { - -voidpf IOSystem2Unzip::open(voidpf opaque, const char* filename, int mode) { - IOSystem* io_system = (IOSystem*) opaque; - - const char* mode_fopen = NULL; - if((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) { - mode_fopen = "rb"; - } else { - if(mode & ZLIB_FILEFUNC_MODE_EXISTING) { - mode_fopen = "r+b"; - } else { - if(mode & ZLIB_FILEFUNC_MODE_CREATE) { - mode_fopen = "wb"; - } - } - } - - return (voidpf) io_system->Open(filename, mode_fopen); -} - -uLong IOSystem2Unzip::read(voidpf /*opaque*/, voidpf stream, void* buf, uLong size) { - IOStream* io_stream = (IOStream*) stream; - - return static_cast(io_stream->Read(buf, 1, size)); -} - -uLong IOSystem2Unzip::write(voidpf /*opaque*/, voidpf stream, const void* buf, uLong size) { - IOStream* io_stream = (IOStream*) stream; - - return static_cast(io_stream->Write(buf, 1, size)); -} - -long IOSystem2Unzip::tell(voidpf /*opaque*/, voidpf stream) { - IOStream* io_stream = (IOStream*) stream; - - return static_cast(io_stream->Tell()); -} - -long IOSystem2Unzip::seek(voidpf /*opaque*/, voidpf stream, uLong offset, int origin) { - IOStream* io_stream = (IOStream*) stream; - - aiOrigin assimp_origin; - switch (origin) { - default: - case ZLIB_FILEFUNC_SEEK_CUR: - assimp_origin = aiOrigin_CUR; - break; - case ZLIB_FILEFUNC_SEEK_END: - assimp_origin = aiOrigin_END; - break; - case ZLIB_FILEFUNC_SEEK_SET: - assimp_origin = aiOrigin_SET; - break; - } - - return (io_stream->Seek(offset, assimp_origin) == aiReturn_SUCCESS ? 0 : -1); -} - -int IOSystem2Unzip::close(voidpf opaque, voidpf stream) { - IOSystem* io_system = (IOSystem*) opaque; - IOStream* io_stream = (IOStream*) stream; - - io_system->Close(io_stream); - - return 0; -} - -int IOSystem2Unzip::testerror(voidpf /*opaque*/, voidpf /*stream*/) { - return 0; -} - -zlib_filefunc_def IOSystem2Unzip::get(IOSystem* pIOHandler) { - zlib_filefunc_def mapping; - - mapping.zopen_file = open; - mapping.zread_file = read; - mapping.zwrite_file = write; - mapping.ztell_file = tell; - mapping.zseek_file = seek; - mapping.zclose_file = close; - mapping.zerror_file = testerror; - mapping.opaque = (voidpf) pIOHandler; - - return mapping; -} - -ZipFile::ZipFile(size_t size) : m_Size(size) { - ai_assert(m_Size != 0); - - m_Buffer = malloc(m_Size); -} - -ZipFile::~ZipFile() { - free(m_Buffer); - m_Buffer = NULL; -} - -size_t ZipFile::Read(void* pvBuffer, size_t pSize, size_t pCount) { - const size_t size = pSize * pCount; - assert(size <= m_Size); - - std::memcpy(pvBuffer, m_Buffer, size); - - return size; -} - -size_t ZipFile::Write(const void* /*pvBuffer*/, size_t /*pSize*/, size_t /*pCount*/) { - return 0; -} - -size_t ZipFile::FileSize() const { - return m_Size; -} - -aiReturn ZipFile::Seek(size_t /*pOffset*/, aiOrigin /*pOrigin*/) { - return aiReturn_FAILURE; -} - -size_t ZipFile::Tell() const { - return 0; -} - -void ZipFile::Flush() { - // empty -} - -// ------------------------------------------------------------------------------------------------ -// Constructor. -Q3BSPZipArchive::Q3BSPZipArchive(IOSystem* pIOHandler, const std::string& rFile) : m_ZipFileHandle(NULL), m_ArchiveMap() { - if (! rFile.empty()) { - zlib_filefunc_def mapping = IOSystem2Unzip::get(pIOHandler); - - m_ZipFileHandle = unzOpen2(rFile.c_str(), &mapping); - - if(m_ZipFileHandle != nullptr) { - mapArchive(); - } - } -} - -// ------------------------------------------------------------------------------------------------ -// Destructor. -Q3BSPZipArchive::~Q3BSPZipArchive() { - for(auto &file : m_ArchiveMap) { - delete file.second; - } - m_ArchiveMap.clear(); - - if(m_ZipFileHandle != nullptr) { - unzClose(m_ZipFileHandle); - m_ZipFileHandle = nullptr; - } -} - -// ------------------------------------------------------------------------------------------------ -// Returns true, if the archive is already open. -bool Q3BSPZipArchive::isOpen() const { - return (m_ZipFileHandle != nullptr); -} - -// ------------------------------------------------------------------------------------------------ -// Returns true, if the filename is part of the archive. -bool Q3BSPZipArchive::Exists(const char* pFile) const { - bool exist = false; - if (pFile != nullptr) { - std::string rFile(pFile); - std::map::const_iterator it = m_ArchiveMap.find(rFile); - - if(it != m_ArchiveMap.end()) { - exist = true; - } - } - - return exist; -} - -// ------------------------------------------------------------------------------------------------ -// Returns the separator delimiter. -char Q3BSPZipArchive::getOsSeparator() const { -#ifndef _WIN32 - return '/'; -#else - return '\\'; -#endif -} - -// ------------------------------------------------------------------------------------------------ -// Opens a file, which is part of the archive. -IOStream *Q3BSPZipArchive::Open(const char* pFile, const char* /*pMode*/) { - ai_assert(pFile != nullptr); - - IOStream* result = nullptr; - - std::map::iterator it = m_ArchiveMap.find(pFile); - - if(it != m_ArchiveMap.end()) { - result = (IOStream*) it->second; - } - - return result; -} - -// ------------------------------------------------------------------------------------------------ -// Close a filestream. -void Q3BSPZipArchive::Close(IOStream *pFile) { - (void)(pFile); - ai_assert(pFile != nullptr); - - // We don't do anything in case the file would be opened again in the future -} -// ------------------------------------------------------------------------------------------------ -// Returns the file-list of the archive. -void Q3BSPZipArchive::getFileList(std::vector &rFileList) { - rFileList.clear(); - - for(auto &file : m_ArchiveMap) { - rFileList.push_back(file.first); - } -} - -// ------------------------------------------------------------------------------------------------ -// Maps the archive content. -bool Q3BSPZipArchive::mapArchive() { - bool success = false; - - if(m_ZipFileHandle != nullptr) { - if(m_ArchiveMap.empty()) { - // At first ensure file is already open - if(unzGoToFirstFile(m_ZipFileHandle) == UNZ_OK) { - // Loop over all files - do { - char filename[FileNameSize]; - unz_file_info fileInfo; - - if(unzGetCurrentFileInfo(m_ZipFileHandle, &fileInfo, filename, FileNameSize, NULL, 0, NULL, 0) == UNZ_OK) { - // The file has EXACTLY the size of uncompressed_size. In C - // you need to mark the last character with '\0', so add - // another character - if(fileInfo.uncompressed_size != 0 && unzOpenCurrentFile(m_ZipFileHandle) == UNZ_OK) { - std::pair::iterator, bool> result = m_ArchiveMap.insert(std::make_pair(filename, new ZipFile(fileInfo.uncompressed_size))); - - if(unzReadCurrentFile(m_ZipFileHandle, result.first->second->m_Buffer, fileInfo.uncompressed_size) == (long int) fileInfo.uncompressed_size) { - if(unzCloseCurrentFile(m_ZipFileHandle) == UNZ_OK) { - // Nothing to do anymore... - } - } - } - } - } while(unzGoToNextFile(m_ZipFileHandle) != UNZ_END_OF_LIST_OF_FILE); - } - } - - success = true; - } - - return success; -} - -// ------------------------------------------------------------------------------------------------ - -} // Namespace Q3BSP -} // Namespace Assimp - -#endif // ASSIMP_BUILD_NO_Q3BSP_IMPORTER diff --git a/third_party/libassimp/code/Q3BSPZipArchive.h b/third_party/libassimp/code/Q3BSPZipArchive.h deleted file mode 100644 index 606f7b183b..0000000000 --- a/third_party/libassimp/code/Q3BSPZipArchive.h +++ /dev/null @@ -1,131 +0,0 @@ -/* -Open Asset Import Library (assimp) ----------------------------------------------------------------------- - -Copyright (c) 2006-2018, 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. - ----------------------------------------------------------------------- -*/ -#ifndef AI_Q3BSP_ZIPARCHIVE_H_INC -#define AI_Q3BSP_ZIPARCHIVE_H_INC - -#include -#include -#include -#include -#include -#include - -namespace Assimp { -namespace Q3BSP { - -// ------------------------------------------------------------------------------------------------ -/// \class IOSystem2Unzip -/// \ingroup Assimp::Q3BSP -/// -/// \brief -// ------------------------------------------------------------------------------------------------ -class IOSystem2Unzip { -public: - static voidpf open(voidpf opaque, const char* filename, int mode); - static uLong read(voidpf opaque, voidpf stream, void* buf, uLong size); - static uLong write(voidpf opaque, voidpf stream, const void* buf, uLong size); - static long tell(voidpf opaque, voidpf stream); - static long seek(voidpf opaque, voidpf stream, uLong offset, int origin); - static int close(voidpf opaque, voidpf stream); - static int testerror(voidpf opaque, voidpf stream); - static zlib_filefunc_def get(IOSystem* pIOHandler); -}; - -// ------------------------------------------------------------------------------------------------ -/// \class ZipFile -/// \ingroup Assimp::Q3BSP -/// -/// \brief -// ------------------------------------------------------------------------------------------------ -class ZipFile : public IOStream { - friend class Q3BSPZipArchive; - -public: - explicit ZipFile(size_t size); - ~ZipFile(); - size_t Read(void* pvBuffer, size_t pSize, size_t pCount ); - size_t Write(const void* /*pvBuffer*/, size_t /*pSize*/, size_t /*pCount*/); - size_t FileSize() const; - aiReturn Seek(size_t /*pOffset*/, aiOrigin /*pOrigin*/); - size_t Tell() const; - void Flush(); - -private: - void* m_Buffer; - size_t m_Size; -}; - -// ------------------------------------------------------------------------------------------------ -/// \class Q3BSPZipArchive -/// \ingroup Assimp::Q3BSP -/// -/// \brief IMplements a zip archive like the WinZip archives. Will be also used to import data -/// from a P3K archive ( Quake level format ). -// ------------------------------------------------------------------------------------------------ -class Q3BSPZipArchive : public Assimp::IOSystem { -public: - static const unsigned int FileNameSize = 256; - -public: - Q3BSPZipArchive(IOSystem* pIOHandler, const std::string & rFile); - ~Q3BSPZipArchive(); - bool Exists(const char* pFile) const; - char getOsSeparator() const; - IOStream* Open(const char* pFile, const char* pMode = "rb"); - void Close(IOStream* pFile); - bool isOpen() const; - void getFileList(std::vector &rFileList); - -private: - bool mapArchive(); - -private: - unzFile m_ZipFileHandle; - std::map m_ArchiveMap; -}; - -// ------------------------------------------------------------------------------------------------ - -} // Namespace Q3BSP -} // Namespace Assimp - -#endif // AI_Q3BSP_ZIPARCHIVE_H_INC diff --git a/third_party/libassimp/code/Q3DLoader.cpp b/third_party/libassimp/code/Q3D/Q3DLoader.cpp similarity index 98% rename from third_party/libassimp/code/Q3DLoader.cpp rename to third_party/libassimp/code/Q3D/Q3DLoader.cpp index f1165dc2c0..b8c8de716c 100644 --- a/third_party/libassimp/code/Q3DLoader.cpp +++ b/third_party/libassimp/code/Q3D/Q3DLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -302,13 +302,14 @@ void Q3DImporter::InternReadFile( const std::string& pFile, case 't': pScene->mNumTextures = numTextures; - if (!numTextures)break; - pScene->mTextures = new aiTexture*[pScene->mNumTextures]; + if (!numTextures) { + break; + } + pScene->mTextures = new aiTexture*[pScene->mNumTextures]; // to make sure we won't crash if we leave through an exception ::memset(pScene->mTextures,0,sizeof(void*)*pScene->mNumTextures); - for (unsigned int i = 0; i < pScene->mNumTextures; ++i) - { - aiTexture* tex = pScene->mTextures[i] = new aiTexture(); + for (unsigned int i = 0; i < pScene->mNumTextures; ++i) { + aiTexture* tex = pScene->mTextures[i] = new aiTexture; // skip the texture name while (stream.GetI1()); @@ -317,15 +318,16 @@ void Q3DImporter::InternReadFile( const std::string& pFile, tex->mWidth = (unsigned int)stream.GetI4(); tex->mHeight = (unsigned int)stream.GetI4(); - if (!tex->mWidth || !tex->mHeight) + if (!tex->mWidth || !tex->mHeight) { throw DeadlyImportError("Quick3D: Invalid texture. Width or height is zero"); + } unsigned int mul = tex->mWidth * tex->mHeight; aiTexel* begin = tex->pcData = new aiTexel[mul]; - aiTexel* const end = & begin [mul]; + aiTexel* const end = & begin[mul-1] +1; - for (;begin != end; ++begin) - { + + for (;begin != end; ++begin) { begin->r = stream.GetI1(); begin->g = stream.GetI1(); begin->b = stream.GetI1(); diff --git a/third_party/libassimp/code/Q3DLoader.h b/third_party/libassimp/code/Q3D/Q3DLoader.h similarity index 99% rename from third_party/libassimp/code/Q3DLoader.h rename to third_party/libassimp/code/Q3D/Q3DLoader.h index bdb104df3d..954d3105cc 100644 --- a/third_party/libassimp/code/Q3DLoader.h +++ b/third_party/libassimp/code/Q3D/Q3DLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/RawLoader.cpp b/third_party/libassimp/code/Raw/RawLoader.cpp similarity index 99% rename from third_party/libassimp/code/RawLoader.cpp rename to third_party/libassimp/code/Raw/RawLoader.cpp index 1bc5087598..d0da247e47 100644 --- a/third_party/libassimp/code/RawLoader.cpp +++ b/third_party/libassimp/code/Raw/RawLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/RawLoader.h b/third_party/libassimp/code/Raw/RawLoader.h similarity index 98% rename from third_party/libassimp/code/RawLoader.h rename to third_party/libassimp/code/Raw/RawLoader.h index f6e894fdde..8bfe8ef98d 100644 --- a/third_party/libassimp/code/RawLoader.h +++ b/third_party/libassimp/code/Raw/RawLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/SIBImporter.cpp b/third_party/libassimp/code/SIB/SIBImporter.cpp similarity index 99% rename from third_party/libassimp/code/SIBImporter.cpp rename to third_party/libassimp/code/SIB/SIBImporter.cpp index 7a69dd1755..20cdc80096 100644 --- a/third_party/libassimp/code/SIBImporter.cpp +++ b/third_party/libassimp/code/SIB/SIBImporter.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -59,8 +59,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include -//#include "../contrib/ConvertUTF/ConvertUTF.h" -#include "../contrib/utf8cpp/source/utf8.h" +#ifdef ASSIMP_USE_HUNTER +# include +#else +//# include "../contrib/ConvertUTF/ConvertUTF.h" +# include "../contrib/utf8cpp/source/utf8.h" +#endif #include #include #include diff --git a/third_party/libassimp/code/SIBImporter.h b/third_party/libassimp/code/SIB/SIBImporter.h similarity index 99% rename from third_party/libassimp/code/SIBImporter.h rename to third_party/libassimp/code/SIB/SIBImporter.h index 9437af5888..bb88c22554 100644 --- a/third_party/libassimp/code/SIBImporter.h +++ b/third_party/libassimp/code/SIB/SIBImporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/SMDLoader.cpp b/third_party/libassimp/code/SMD/SMDLoader.cpp similarity index 99% rename from third_party/libassimp/code/SMDLoader.cpp rename to third_party/libassimp/code/SMD/SMDLoader.cpp index c6ec616243..4288bf9c3a 100644 --- a/third_party/libassimp/code/SMDLoader.cpp +++ b/third_party/libassimp/code/SMD/SMDLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -486,7 +486,7 @@ void SMDImporter::CreateOutputAnimations(const std::string &pFile, IOSystem* pIO if (bLoadAnimationList) { GetAnimationFileList(pFile, pIOHandler, animFileList); } - int animCount = animFileList.size() + 1; + int animCount = static_cast( animFileList.size() + 1u ); pScene->mNumAnimations = 1; pScene->mAnimations = new aiAnimation*[animCount]; memset(pScene->mAnimations, 0, sizeof(aiAnimation*)*animCount); @@ -510,7 +510,7 @@ void SMDImporter::CreateOutputAnimation(int index, const std::string &name) { anim->mName.Set(name.c_str()); } anim->mDuration = dLengthOfAnim; - anim->mNumChannels = asBones.size(); + anim->mNumChannels = static_cast( asBones.size() ); anim->mTicksPerSecond = 25.0; // FIXME: is this correct? aiNodeAnim** pp = anim->mChannels = new aiNodeAnim*[anim->mNumChannels]; diff --git a/third_party/libassimp/code/SMDLoader.h b/third_party/libassimp/code/SMD/SMDLoader.h similarity index 99% rename from third_party/libassimp/code/SMDLoader.h rename to third_party/libassimp/code/SMD/SMDLoader.h index a791e7dde3..85dac97d1c 100644 --- a/third_party/libassimp/code/SMDLoader.h +++ b/third_party/libassimp/code/SMD/SMDLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/STLExporter.cpp b/third_party/libassimp/code/STL/STLExporter.cpp similarity index 97% rename from third_party/libassimp/code/STLExporter.cpp rename to third_party/libassimp/code/STL/STLExporter.cpp index e4a1dbb66f..43bc752ae8 100644 --- a/third_party/libassimp/code/STLExporter.cpp +++ b/third_party/libassimp/code/STL/STLExporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -111,7 +111,7 @@ STLExporter::STLExporter(const char* _filename, const aiScene* pScene, bool expo // make sure that all formatting happens using the standard, C locale and not the user's current locale const std::locale& l = std::locale("C"); mOutput.imbue(l); - mOutput.precision(16); + mOutput.precision(ASSIMP_AI_REAL_TEXT_PRECISION); if (binary) { char buf[80] = {0} ; buf[0] = 'A'; buf[1] = 's'; buf[2] = 's'; buf[3] = 'i'; buf[4] = 'm'; buf[5] = 'p'; @@ -127,7 +127,7 @@ STLExporter::STLExporter(const char* _filename, const aiScene* pScene, bool expo mOutput.write((char *)&meshnum, 4); if (exportPointClouds) { - + throw DeadlyExportError("This functionality is not yet implemented for binary output."); } for(unsigned int i = 0; i < pScene->mNumMeshes; ++i) { diff --git a/third_party/libassimp/code/STLExporter.h b/third_party/libassimp/code/STL/STLExporter.h similarity index 98% rename from third_party/libassimp/code/STLExporter.h rename to third_party/libassimp/code/STL/STLExporter.h index 6e8f909150..cb5238e60f 100644 --- a/third_party/libassimp/code/STLExporter.h +++ b/third_party/libassimp/code/STL/STLExporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/STLLoader.cpp b/third_party/libassimp/code/STL/STLLoader.cpp similarity index 98% rename from third_party/libassimp/code/STLLoader.cpp rename to third_party/libassimp/code/STL/STLLoader.cpp index fb866bb7a0..199a84a443 100644 --- a/third_party/libassimp/code/STLLoader.cpp +++ b/third_party/libassimp/code/STL/STLLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -182,7 +182,7 @@ void STLImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOS std::unique_ptr file( pIOHandler->Open( pFile, "rb")); // Check whether we can read from the file - if( file.get() == NULL) { + if( file.get() == nullptr) { throw DeadlyImportError( "Failed to open STL file " + pFile + "."); } @@ -190,11 +190,11 @@ void STLImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOS // allocate storage and copy the contents of the file to a memory buffer // (terminate it with zero) - std::vector mBuffer2; - TextFileToBuffer(file.get(),mBuffer2); + std::vector buffer2; + TextFileToBuffer(file.get(),buffer2); this->pScene = pScene; - this->mBuffer = &mBuffer2[0]; + this->mBuffer = &buffer2[0]; // the default vertex color is light gray. clrColorDefault.r = clrColorDefault.g = clrColorDefault.b = clrColorDefault.a = (ai_real) 0.6; @@ -225,12 +225,14 @@ void STLImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOS } pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_DIFFUSE); pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_SPECULAR); - clrDiffuse = aiColor4D( ai_real(1.0), ai_real(1.0), ai_real(1.0), ai_real(1.0)); + clrDiffuse = aiColor4D( ai_real(0.05), ai_real(0.05), ai_real(0.05), ai_real(1.0)); pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_AMBIENT); pScene->mNumMaterials = 1; pScene->mMaterials = new aiMaterial*[1]; pScene->mMaterials[0] = pcMat; + + mBuffer = nullptr; } // ------------------------------------------------------------------------------------------------ @@ -276,6 +278,7 @@ void STLImporter::LoadASCIIFile( aiNode *root ) { } std::string name( szMe, temp ); node->mName.Set( name.c_str() ); + pMesh->mName.Set( name.c_str() ); //pScene->mRootNode->mName.length = temp; //memcpy(pScene->mRootNode->mName.data,szMe,temp); //pScene->mRootNode->mName.data[temp] = '\0'; diff --git a/third_party/libassimp/code/STLLoader.h b/third_party/libassimp/code/STL/STLLoader.h similarity index 98% rename from third_party/libassimp/code/STLLoader.h rename to third_party/libassimp/code/STL/STLLoader.h index 3b87f70a33..ca1011cb81 100644 --- a/third_party/libassimp/code/STLLoader.h +++ b/third_party/libassimp/code/STL/STLLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/STEPFile.h b/third_party/libassimp/code/Step/STEPFile.h similarity index 99% rename from third_party/libassimp/code/STEPFile.h rename to third_party/libassimp/code/Step/STEPFile.h index f5b56c31f5..d99b34b3ca 100644 --- a/third_party/libassimp/code/STEPFile.h +++ b/third_party/libassimp/code/Step/STEPFile.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -50,7 +50,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include "FBXDocument.h" //ObjectMap::value_type +#include "FBX/FBXDocument.h" //ObjectMap::value_type + #include // diff --git a/third_party/libassimp/code/StepExporter.cpp b/third_party/libassimp/code/Step/StepExporter.cpp similarity index 96% rename from third_party/libassimp/code/StepExporter.cpp rename to third_party/libassimp/code/Step/StepExporter.cpp index 4368201b76..70035d9ea6 100644 --- a/third_party/libassimp/code/StepExporter.cpp +++ b/third_party/libassimp/code/Step/StepExporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -45,23 +45,25 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_EXPORT #ifndef ASSIMP_BUILD_NO_STEP_EXPORTER -#include "StepExporter.h" -#include "ConvertToLHProcess.h" +#include "Step/StepExporter.h" +#include "PostProcessing/ConvertToLHProcess.h" + #include #include #include #include +#include +#include +#include +#include +#include + #include #include #include #include #include #include -#include -#include -#include -#include -#include // #if _MSC_VER > 1500 || (defined __GNUC___) @@ -141,15 +143,15 @@ namespace { // ------------------------------------------------------------------------------------------------ // Constructor for a specific scene to export StepExporter::StepExporter(const aiScene* pScene, IOSystem* pIOSystem, const std::string& path, - const std::string& file, const ExportProperties* pProperties): - mProperties(pProperties),mIOSystem(pIOSystem),mFile(file), mPath(path), - mScene(pScene), endstr(";\n") { - CollectTrafos(pScene->mRootNode, trafos); - CollectMeshes(pScene->mRootNode, meshes); + const std::string& file, const ExportProperties* pProperties) : + mProperties(pProperties), mIOSystem(pIOSystem), mFile(file), mPath(path), + mScene(pScene), endstr(";\n") { + CollectTrafos(pScene->mRootNode, trafos); + CollectMeshes(pScene->mRootNode, meshes); // make sure that all formatting happens using the standard, C locale and not the user's current locale - mOutput.imbue( std::locale("C") ); - mOutput.precision(16); + mOutput.imbue(std::locale("C")); + mOutput.precision(ASSIMP_AI_REAL_TEXT_PRECISION); // start writing WriteFile(); @@ -164,7 +166,7 @@ void StepExporter::WriteFile() mOutput.setf(std::ios::fixed); // precision for double // see http://stackoverflow.com/questions/554063/how-do-i-print-a-double-value-with-full-precision-using-cout - mOutput.precision(16); + mOutput.precision(ASSIMP_AI_REAL_TEXT_PRECISION); // standard color aiColor4D fColor; diff --git a/third_party/libassimp/code/StepExporter.h b/third_party/libassimp/code/Step/StepExporter.h similarity index 98% rename from third_party/libassimp/code/StepExporter.h rename to third_party/libassimp/code/Step/StepExporter.h index f1323bee8e..f96a0d2b56 100644 --- a/third_party/libassimp/code/StepExporter.h +++ b/third_party/libassimp/code/Step/StepExporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/TerragenLoader.cpp b/third_party/libassimp/code/Terragen/TerragenLoader.cpp similarity index 99% rename from third_party/libassimp/code/TerragenLoader.cpp rename to third_party/libassimp/code/Terragen/TerragenLoader.cpp index 0eb22cef6d..9b0873c681 100644 --- a/third_party/libassimp/code/TerragenLoader.cpp +++ b/third_party/libassimp/code/Terragen/TerragenLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/code/TerragenLoader.h b/third_party/libassimp/code/Terragen/TerragenLoader.h similarity index 98% rename from third_party/libassimp/code/TerragenLoader.h rename to third_party/libassimp/code/Terragen/TerragenLoader.h index a02889de1e..a478c0dcd8 100644 --- a/third_party/libassimp/code/TerragenLoader.h +++ b/third_party/libassimp/code/Terragen/TerragenLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/UnrealLoader.cpp b/third_party/libassimp/code/Unreal/UnrealLoader.cpp similarity index 99% rename from third_party/libassimp/code/UnrealLoader.cpp rename to third_party/libassimp/code/Unreal/UnrealLoader.cpp index 64bfbb9e00..0bd4650d0f 100644 --- a/third_party/libassimp/code/UnrealLoader.cpp +++ b/third_party/libassimp/code/Unreal/UnrealLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -52,12 +52,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_3D_IMPORTER -#include "UnrealLoader.h" +#include "Unreal/UnrealLoader.h" +#include "PostProcessing/ConvertToLHProcess.h" + #include #include #include -#include "ConvertToLHProcess.h" - #include #include #include diff --git a/third_party/libassimp/code/UnrealLoader.h b/third_party/libassimp/code/Unreal/UnrealLoader.h similarity index 98% rename from third_party/libassimp/code/UnrealLoader.h rename to third_party/libassimp/code/Unreal/UnrealLoader.h index 4095aa142a..678aaa76bb 100644 --- a/third_party/libassimp/code/UnrealLoader.h +++ b/third_party/libassimp/code/Unreal/UnrealLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -127,7 +127,8 @@ inline void CompressVertex(const aiVector3D& v, uint32_t& out) n.X = (int32_t)v.x; n.Y = (int32_t)v.y; n.Z = (int32_t)v.z; - out = t; + ::memcpy( &out, &t, sizeof(int32_t)); + //out = t; } // UNREAL vertex decompression diff --git a/third_party/libassimp/code/XFileExporter.cpp b/third_party/libassimp/code/X/XFileExporter.cpp similarity index 98% rename from third_party/libassimp/code/XFileExporter.cpp rename to third_party/libassimp/code/X/XFileExporter.cpp index 1510ae6d49..ae9fd58fc1 100644 --- a/third_party/libassimp/code/XFileExporter.cpp +++ b/third_party/libassimp/code/X/XFileExporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -45,21 +45,23 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_EXPORT #ifndef ASSIMP_BUILD_NO_X_EXPORTER -#include "XFileExporter.h" -#include "ConvertToLHProcess.h" +#include "X/XFileExporter.h" +#include "PostProcessing/ConvertToLHProcess.h" + #include #include #include #include #include -#include -#include -#include #include #include #include #include +#include +#include +#include + using namespace Assimp; namespace Assimp @@ -111,7 +113,7 @@ XFileExporter::XFileExporter(const aiScene* pScene, IOSystem* pIOSystem, const s { // make sure that all formatting happens using the standard, C locale and not the user's current locale mOutput.imbue( std::locale("C") ); - mOutput.precision(16); + mOutput.precision(ASSIMP_AI_REAL_TEXT_PRECISION); // start writing WriteFile(); @@ -132,7 +134,7 @@ void XFileExporter::WriteFile() { // note, that all realnumber values must be comma separated in x files mOutput.setf(std::ios::fixed); - mOutput.precision(16); // precision for double + mOutput.precision(ASSIMP_AI_REAL_TEXT_PRECISION); // precision for ai_real // entry of writing the file WriteHeader(); diff --git a/third_party/libassimp/code/XFileExporter.h b/third_party/libassimp/code/X/XFileExporter.h similarity index 99% rename from third_party/libassimp/code/XFileExporter.h rename to third_party/libassimp/code/X/XFileExporter.h index fc480f40b5..322440af8c 100644 --- a/third_party/libassimp/code/XFileExporter.h +++ b/third_party/libassimp/code/X/XFileExporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/XFileHelper.h b/third_party/libassimp/code/X/XFileHelper.h similarity index 99% rename from third_party/libassimp/code/XFileHelper.h rename to third_party/libassimp/code/X/XFileHelper.h index c51e2eba96..0365280f07 100644 --- a/third_party/libassimp/code/XFileHelper.h +++ b/third_party/libassimp/code/X/XFileHelper.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/XFileImporter.cpp b/third_party/libassimp/code/X/XFileImporter.cpp similarity index 98% rename from third_party/libassimp/code/XFileImporter.cpp rename to third_party/libassimp/code/X/XFileImporter.cpp index ae847eef86..be7256d5c7 100644 --- a/third_party/libassimp/code/XFileImporter.cpp +++ b/third_party/libassimp/code/X/XFileImporter.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -44,10 +44,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_X_IMPORTER -#include "XFileImporter.h" -#include "XFileParser.h" +#include "X/XFileImporter.h" +#include "X/XFileParser.h" +#include "PostProcessing/ConvertToLHProcess.h" + #include -#include "ConvertToLHProcess.h" #include #include #include @@ -331,7 +332,7 @@ void XFileImporter::CreateMeshes( aiScene* pScene, aiNode* pNode, const std::vec // collect vertex data for indices of this face for( unsigned int d = 0; d < df.mNumIndices; ++d ) { - df.mIndices[d] = newIndex; + df.mIndices[ d ] = newIndex; const unsigned int newIdx( pf.mIndices[ d ] ); if ( newIdx > sourceMesh->mPositions.size() ) { continue; @@ -343,7 +344,10 @@ void XFileImporter::CreateMeshes( aiScene* pScene, aiNode* pNode, const std::vec mesh->mVertices[newIndex] = sourceMesh->mPositions[pf.mIndices[d]]; // Normal, if present if ( mesh->HasNormals() ) { - mesh->mNormals[ newIndex ] = sourceMesh->mNormals[ sourceMesh->mNormFaces[ f ].mIndices[ d ] ]; + if ( sourceMesh->mNormFaces[ f ].mIndices.size() > d ) { + const size_t idx( sourceMesh->mNormFaces[ f ].mIndices[ d ] ); + mesh->mNormals[ newIndex ] = sourceMesh->mNormals[ idx ]; + } } // texture coord sets diff --git a/third_party/libassimp/code/XFileImporter.h b/third_party/libassimp/code/X/XFileImporter.h similarity index 98% rename from third_party/libassimp/code/XFileImporter.h rename to third_party/libassimp/code/X/XFileImporter.h index b3c06eab11..7d12b6fdf6 100644 --- a/third_party/libassimp/code/XFileImporter.h +++ b/third_party/libassimp/code/X/XFileImporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -58,13 +58,13 @@ struct aiNode; namespace Assimp { namespace XFile { -struct Scene; -struct Node; + struct Scene; + struct Node; } // --------------------------------------------------------------------------- /** The XFileImporter is a worker class capable of importing a scene from a - * DirectX file .x + * DirectX file .x */ class XFileImporter : public BaseImporter { public: diff --git a/third_party/libassimp/code/XFileParser.cpp b/third_party/libassimp/code/X/XFileParser.cpp similarity index 98% rename from third_party/libassimp/code/XFileParser.cpp rename to third_party/libassimp/code/X/XFileParser.cpp index e7bf8518c8..8fcf87cf62 100644 --- a/third_party/libassimp/code/XFileParser.cpp +++ b/third_party/libassimp/code/X/XFileParser.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -583,24 +583,30 @@ void XFileParser::ParseDataObjectMeshNormals( Mesh* pMesh) pMesh->mNormals.resize( numNormals); // read normal vectors - for( unsigned int a = 0; a < numNormals; a++) + for( unsigned int a = 0; a < numNormals; ++a) { pMesh->mNormals[a] = ReadVector3(); + } // read normal indices unsigned int numFaces = ReadInt(); - if( numFaces != pMesh->mPosFaces.size()) + if( numFaces != pMesh->mPosFaces.size()) { ThrowException( "Normal face count does not match vertex face count."); + } - for( unsigned int a = 0; a < numFaces; a++) - { - unsigned int numIndices = ReadInt(); - pMesh->mNormFaces.push_back( Face()); - Face& face = pMesh->mNormFaces.back(); + // do not crah when no face definitions are there + if (numFaces > 0) { + // normal face creation + pMesh->mNormFaces.resize( numFaces ); + for( unsigned int a = 0; a < numFaces; ++a ) { + unsigned int numIndices = ReadInt(); + pMesh->mNormFaces[a] = Face(); + Face& face = pMesh->mNormFaces[a]; + for( unsigned int b = 0; b < numIndices; ++b ) { + face.mIndices.push_back( ReadInt()); + } - for( unsigned int b = 0; b < numIndices; b++) - face.mIndices.push_back( ReadInt()); - - TestForSeparator(); + TestForSeparator(); + } } CheckForClosingBrace(); diff --git a/third_party/libassimp/code/XFileParser.h b/third_party/libassimp/code/X/XFileParser.h similarity index 99% rename from third_party/libassimp/code/XFileParser.h rename to third_party/libassimp/code/X/XFileParser.h index 24eb6104d5..993bae6a1c 100644 --- a/third_party/libassimp/code/XFileParser.h +++ b/third_party/libassimp/code/X/XFileParser.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/FIReader.cpp b/third_party/libassimp/code/X3D/FIReader.cpp old mode 100755 new mode 100644 similarity index 99% rename from third_party/libassimp/code/FIReader.cpp rename to third_party/libassimp/code/X3D/FIReader.cpp index bdc447b341..9bb2c69f60 --- a/third_party/libassimp/code/FIReader.cpp +++ b/third_party/libassimp/code/X3D/FIReader.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -60,7 +60,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include -#include "../contrib/utf8cpp/source/utf8.h" +#ifdef ASSIMP_USE_HUNTER +# include +#else +# include "../contrib/utf8cpp/source/utf8.h" +#endif #include #include #include diff --git a/third_party/libassimp/code/FIReader.hpp b/third_party/libassimp/code/X3D/FIReader.hpp similarity index 97% rename from third_party/libassimp/code/FIReader.hpp rename to third_party/libassimp/code/X3D/FIReader.hpp index 9ff752d5cc..2c92239aca 100644 --- a/third_party/libassimp/code/FIReader.hpp +++ b/third_party/libassimp/code/X3D/FIReader.hpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -57,7 +57,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include //#include //#include -#include +#ifdef ASSIMP_USE_HUNTER +# include +#else +# include +#endif namespace Assimp { diff --git a/third_party/libassimp/code/X3DExporter.cpp b/third_party/libassimp/code/X3D/X3DExporter.cpp similarity index 99% rename from third_party/libassimp/code/X3DExporter.cpp rename to third_party/libassimp/code/X3D/X3DExporter.cpp index 9839e6ca6f..e5eeb0886a 100644 --- a/third_party/libassimp/code/X3DExporter.cpp +++ b/third_party/libassimp/code/X3D/X3DExporter.cpp @@ -68,7 +68,7 @@ aiMatrix4x4 out_matr; } // multiplicate all matrices in reverse order - for(std::list::reverse_iterator rit = matr.rbegin(); rit != matr.rend(); rit++) out_matr = out_matr * (*rit); + for(std::list::reverse_iterator rit = matr.rbegin(); rit != matr.rend(); ++rit) out_matr = out_matr * (*rit); return out_matr; } diff --git a/third_party/libassimp/code/X3DExporter.hpp b/third_party/libassimp/code/X3D/X3DExporter.hpp similarity index 100% rename from third_party/libassimp/code/X3DExporter.hpp rename to third_party/libassimp/code/X3D/X3DExporter.hpp diff --git a/third_party/libassimp/code/X3DImporter.cpp b/third_party/libassimp/code/X3D/X3DImporter.cpp similarity index 97% rename from third_party/libassimp/code/X3DImporter.cpp rename to third_party/libassimp/code/X3D/X3DImporter.cpp index e6c915e908..367d84fcfa 100644 --- a/third_party/libassimp/code/X3DImporter.cpp +++ b/third_party/libassimp/code/X3D/X3DImporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -80,7 +80,13 @@ const aiImporterDesc X3DImporter::Description = { //const std::regex X3DImporter::pattern_nws(R"([^, \t\r\n]+)"); //const std::regex X3DImporter::pattern_true(R"(^\s*(?:true|1)\s*$)", std::regex::icase); -struct WordIterator: public std::iterator { +struct WordIterator { + using iterator_category = std::input_iterator_tag; + using value_type = const char*; + using difference_type = ptrdiff_t; + using pointer = value_type*; + using reference = value_type&; + static const char *whitespace; const char *start_, *end_; WordIterator(const char *start, const char *end): start_(start), end_(end) { @@ -130,8 +136,8 @@ X3DImporter::~X3DImporter() { void X3DImporter::Clear() { NodeElement_Cur = nullptr; // Delete all elements - if(NodeElement_List.size()) { - for ( std::list::iterator it = NodeElement_List.begin(); it != NodeElement_List.end(); it++ ) { + if(!NodeElement_List.empty()) { + for ( std::list::iterator it = NodeElement_List.begin(); it != NodeElement_List.end(); ++it ) { delete *it; } NodeElement_List.clear(); @@ -145,7 +151,7 @@ void X3DImporter::Clear() { bool X3DImporter::FindNodeElement_FromRoot(const std::string& pID, const CX3DImporter_NodeElement::EType pType, CX3DImporter_NodeElement** pElement) { - for(std::list::iterator it = NodeElement_List.begin(); it != NodeElement_List.end(); it++) + for(std::list::iterator it = NodeElement_List.begin(); it != NodeElement_List.end(); ++it) { if(((*it)->Type == pType) && ((*it)->ID == pID)) { @@ -176,7 +182,7 @@ bool X3DImporter::FindNodeElement_FromNode(CX3DImporter_NodeElement* pStartNode, }// if((pStartNode->Type() == pType) && (pStartNode->ID() == pID)) // Check childs of pStartNode. - for(std::list::iterator ch_it = pStartNode->Child.begin(); ch_it != pStartNode->Child.end(); ch_it++) + for(std::list::iterator ch_it = pStartNode->Child.begin(); ch_it != pStartNode->Child.end(); ++ch_it) { found = FindNodeElement_FromNode(*ch_it, pID, pType, pElement); if ( found ) @@ -608,10 +614,10 @@ void X3DImporter::XML_ReadNode_GetAttrVal_AsArrCol3f(const int pAttrIdx, std::ve XML_ReadNode_GetAttrVal_AsListCol3f(pAttrIdx, tlist);// read as list // and copy to array - if(tlist.size() > 0) + if(!tlist.empty()) { pValue.reserve(tlist.size()); - for(std::list::iterator it = tlist.begin(); it != tlist.end(); it++) pValue.push_back(*it); + for(std::list::iterator it = tlist.begin(); it != tlist.end(); ++it) pValue.push_back(*it); } } @@ -641,10 +647,10 @@ void X3DImporter::XML_ReadNode_GetAttrVal_AsArrCol4f(const int pAttrIdx, std::ve XML_ReadNode_GetAttrVal_AsListCol4f(pAttrIdx, tlist);// read as list // and copy to array - if(tlist.size() > 0) + if(!tlist.empty()) { pValue.reserve(tlist.size()); - for ( std::list::iterator it = tlist.begin(); it != tlist.end(); it++ ) + for ( std::list::iterator it = tlist.begin(); it != tlist.end(); ++it ) { pValue.push_back( *it ); } @@ -678,10 +684,10 @@ void X3DImporter::XML_ReadNode_GetAttrVal_AsArrVec2f(const int pAttrIdx, std::ve XML_ReadNode_GetAttrVal_AsListVec2f(pAttrIdx, tlist);// read as list // and copy to array - if(tlist.size() > 0) + if(!tlist.empty()) { pValue.reserve(tlist.size()); - for ( std::list::iterator it = tlist.begin(); it != tlist.end(); it++ ) + for ( std::list::iterator it = tlist.begin(); it != tlist.end(); ++it ) { pValue.push_back( *it ); } @@ -716,10 +722,10 @@ void X3DImporter::XML_ReadNode_GetAttrVal_AsArrVec3f(const int pAttrIdx, std::ve XML_ReadNode_GetAttrVal_AsListVec3f(pAttrIdx, tlist);// read as list // and copy to array - if(tlist.size() > 0) + if(!tlist.empty()) { pValue.reserve(tlist.size()); - for ( std::list::iterator it = tlist.begin(); it != tlist.end(); it++ ) + for ( std::list::iterator it = tlist.begin(); it != tlist.end(); ++it ) { pValue.push_back( *it ); } @@ -817,7 +823,7 @@ void X3DImporter::GeometryHelper_Extend_PointToLine(const std::list& std::list::const_iterator pit = pPoint.begin(); std::list::const_iterator pit_last = pPoint.end(); - pit_last--; + --pit_last; if ( pPoint.size() < 2 ) { @@ -831,7 +837,7 @@ void X3DImporter::GeometryHelper_Extend_PointToLine(const std::list& { pLine.push_back(*pit);// second point of previous line pLine.push_back(*pit);// first point of next line - pit++; + ++pit; } // add last point of last line pLine.push_back(*pit); @@ -849,7 +855,7 @@ void X3DImporter::GeometryHelper_Extend_PolylineIdxToLineIdx(const std::list::const_iterator plit_next; - plit_next = plit, plit_next++; + plit_next = plit, ++plit_next; pLineCoordIdx.push_back(*plit);// second point of previous line. pLineCoordIdx.push_back(-1);// delimiter if((*plit_next == (-1)) || (plit_next == pPolylineCoordIdx.end())) break;// current polyline is finished @@ -904,7 +910,7 @@ void X3DImporter::GeometryHelper_CoordIdxStr2FacesArr(const std::vector pFaces.reserve(f_data.size() / 3); inds.reserve(4); //PrintVectorSet("build. ci", pCoordIdx); - for(std::vector::iterator it = f_data.begin(); it != f_data.end(); it++) + for(std::vector::iterator it = f_data.begin(); it != f_data.end(); ++it) { // when face is got count how many indices in it. if(*it == (-1)) @@ -951,7 +957,7 @@ void X3DImporter::MeshGeometry_AddColor(aiMesh& pMesh, const std::list tcol; // create RGBA array from RGB. - for(std::list::const_iterator it = pColors.begin(); it != pColors.end(); it++) tcol.push_back(aiColor4D((*it).r, (*it).g, (*it).b, 1)); + for(std::list::const_iterator it = pColors.begin(); it != pColors.end(); ++it) tcol.push_back(aiColor4D((*it).r, (*it).g, (*it).b, 1)); // call existing function for adding RGBA colors MeshGeometry_AddColor(pMesh, tcol, pColorPerVertex); @@ -991,7 +997,7 @@ void X3DImporter::MeshGeometry_AddColor(aiMesh& pMesh, const std::list tcol; // create RGBA array from RGB. - for ( std::list::const_iterator it = pColors.begin(); it != pColors.end(); it++ ) + for ( std::list::const_iterator it = pColors.begin(); it != pColors.end(); ++it ) { tcol.push_back( aiColor4D( ( *it ).r, ( *it ).g, ( *it ).b, 1 ) ); } @@ -1025,7 +1031,7 @@ void X3DImporter::MeshGeometry_AddColor(aiMesh& pMesh, const std::vector::const_iterator it = pColors.begin(); it != pColors.end(); it++ ) + for ( std::list::const_iterator it = pColors.begin(); it != pColors.end(); ++it ) { col_arr_copy.push_back( *it ); } @@ -1042,7 +1048,7 @@ void X3DImporter::MeshGeometry_AddColor(aiMesh& pMesh, const std::vector::const_iterator colidx_it = pColorIdx.begin(), coordidx_it = pCoordIdx.begin(); colidx_it != pColorIdx.end(); colidx_it++, coordidx_it++) + for(std::vector::const_iterator colidx_it = pColorIdx.begin(), coordidx_it = pCoordIdx.begin(); colidx_it != pColorIdx.end(); ++colidx_it, ++coordidx_it) { if ( *colidx_it == ( -1 ) ) { @@ -1115,7 +1121,7 @@ void X3DImporter::MeshGeometry_AddColor(aiMesh& pMesh, const std::vector::const_iterator it = col_tgt_arr.begin(); it != col_tgt_arr.end(); it++) col_tgt_list.push_back(*it); + for(std::vector::const_iterator it = col_tgt_arr.begin(); it != col_tgt_arr.end(); ++it) col_tgt_list.push_back(*it); // add prepared colors list to mesh. MeshGeometry_AddColor(pMesh, col_tgt_list, pColorPerVertex); } @@ -1128,7 +1134,7 @@ void X3DImporter::MeshGeometry_AddNormal(aiMesh& pMesh, const std::vector::const_iterator it = pNormals.begin(); it != pNormals.end(); it++ ) + for ( std::list::const_iterator it = pNormals.begin(); it != pNormals.end(); ++it ) { norm_arr_copy.push_back( *it ); } @@ -1141,7 +1147,7 @@ void X3DImporter::MeshGeometry_AddNormal(aiMesh& pMesh, const std::vector::const_iterator it = pNormalIdx.begin(); it != pNormalIdx.end(); it++) + for(std::vector::const_iterator it = pNormalIdx.begin(); it != pNormalIdx.end(); ++it) { if(*it != (-1)) tind.push_back(*it); } @@ -1221,7 +1227,7 @@ void X3DImporter::MeshGeometry_AddNormal(aiMesh& pMesh, const std::list::const_iterator it = pTexCoords.begin(); it != pTexCoords.end(); it++) + for(std::list::const_iterator it = pTexCoords.begin(); it != pTexCoords.end(); ++it) { texcoord_arr_copy.push_back(aiVector3D((*it).x, (*it).y, 0)); } @@ -1285,7 +1291,7 @@ void X3DImporter::MeshGeometry_AddTexCoord(aiMesh& pMesh, const std::list::const_iterator it = pTexCoords.begin(); it != pTexCoords.end(); it++ ) + for ( std::list::const_iterator it = pTexCoords.begin(); it != pTexCoords.end(); ++it ) { tc_arr_copy.push_back( aiVector3D( ( *it ).x, ( *it ).y, 0 ) ); } @@ -1693,7 +1699,7 @@ void X3DImporter::InternReadFile(const std::string& pFile, aiScene* pScene, IOSy // create nodes tree Postprocess_BuildNode(*NodeElement_Cur, *pScene->mRootNode, mesh_list, mat_list, light_list); // copy needed data to scene - if(mesh_list.size() > 0) + if(!mesh_list.empty()) { std::list::const_iterator it = mesh_list.begin(); @@ -1702,7 +1708,7 @@ void X3DImporter::InternReadFile(const std::string& pFile, aiScene* pScene, IOSy for(size_t i = 0; i < pScene->mNumMeshes; i++) pScene->mMeshes[i] = *it++; } - if(mat_list.size() > 0) + if(!mat_list.empty()) { std::list::const_iterator it = mat_list.begin(); @@ -1711,7 +1717,7 @@ void X3DImporter::InternReadFile(const std::string& pFile, aiScene* pScene, IOSy for(size_t i = 0; i < pScene->mNumMaterials; i++) pScene->mMaterials[i] = *it++; } - if(light_list.size() > 0) + if(!light_list.empty()) { std::list::const_iterator it = light_list.begin(); diff --git a/third_party/libassimp/code/X3DImporter.hpp b/third_party/libassimp/code/X3D/X3DImporter.hpp similarity index 99% rename from third_party/libassimp/code/X3DImporter.hpp rename to third_party/libassimp/code/X3D/X3DImporter.hpp index 1c9dc5486b..a4afc14631 100644 --- a/third_party/libassimp/code/X3DImporter.hpp +++ b/third_party/libassimp/code/X3D/X3DImporter.hpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/X3DImporter_Geometry2D.cpp b/third_party/libassimp/code/X3D/X3DImporter_Geometry2D.cpp similarity index 99% rename from third_party/libassimp/code/X3DImporter_Geometry2D.cpp rename to third_party/libassimp/code/X3D/X3DImporter_Geometry2D.cpp index 5229017b30..350fd6c405 100644 --- a/third_party/libassimp/code/X3DImporter_Geometry2D.cpp +++ b/third_party/libassimp/code/X3D/X3DImporter_Geometry2D.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -356,7 +356,7 @@ void X3DImporter::ParseNode_Geometry2D_Polyline2D() std::list tlist; // convert vec2 to vec3 - for(std::list::iterator it2 = lineSegments.begin(); it2 != lineSegments.end(); it2++) tlist.push_back(aiVector3D(it2->x, it2->y, 0)); + for(std::list::iterator it2 = lineSegments.begin(); it2 != lineSegments.end(); ++it2) tlist.push_back(aiVector3D(it2->x, it2->y, 0)); // convert point set to line set GeometryHelper_Extend_PointToLine(tlist, ((CX3DImporter_NodeElement_Geometry2D*)ne)->Vertices); @@ -399,7 +399,7 @@ void X3DImporter::ParseNode_Geometry2D_Polypoint2D() if(!def.empty()) ne->ID = def; // convert vec2 to vec3 - for(std::list::iterator it2 = point.begin(); it2 != point.end(); it2++) + for(std::list::iterator it2 = point.begin(); it2 != point.end(); ++it2) { ((CX3DImporter_NodeElement_Geometry2D*)ne)->Vertices.push_back(aiVector3D(it2->x, it2->y, 0)); } @@ -500,7 +500,7 @@ void X3DImporter::ParseNode_Geometry2D_TriangleSet2D() if(!def.empty()) ne->ID = def; // convert vec2 to vec3 - for(std::list::iterator it2 = vertices.begin(); it2 != vertices.end(); it2++) + for(std::list::iterator it2 = vertices.begin(); it2 != vertices.end(); ++it2) { ((CX3DImporter_NodeElement_Geometry2D*)ne)->Vertices.push_back(aiVector3D(it2->x, it2->y, 0)); } diff --git a/third_party/libassimp/code/X3DImporter_Geometry3D.cpp b/third_party/libassimp/code/X3D/X3DImporter_Geometry3D.cpp similarity index 99% rename from third_party/libassimp/code/X3DImporter_Geometry3D.cpp rename to third_party/libassimp/code/X3D/X3DImporter_Geometry3D.cpp index b6d1300989..e12cbd3ab9 100644 --- a/third_party/libassimp/code/X3DImporter_Geometry3D.cpp +++ b/third_party/libassimp/code/X3D/X3DImporter_Geometry3D.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -153,11 +153,11 @@ void X3DImporter::ParseNode_Geometry3D_Cone() { StandardShapes::MakeCircle(bottomRadius, tess, tvec); height = -(height / 2); - for(std::vector::iterator it = tvec.begin(); it != tvec.end(); it++) it->y = height;// y - because circle made in oXZ. + for(std::vector::iterator it = tvec.begin(); it != tvec.end(); ++it) it->y = height;// y - because circle made in oXZ. } // copy data from temp array - for(std::vector::iterator it = tvec.begin(); it != tvec.end(); it++) ((CX3DImporter_NodeElement_Geometry3D*)ne)->Vertices.push_back(*it); + for(std::vector::iterator it = tvec.begin(); it != tvec.end(); ++it) ((CX3DImporter_NodeElement_Geometry3D*)ne)->Vertices.push_back(*it); ((CX3DImporter_NodeElement_Geometry3D*)ne)->Solid = solid; ((CX3DImporter_NodeElement_Geometry3D*)ne)->NumIndices = 3; @@ -226,11 +226,11 @@ void X3DImporter::ParseNode_Geometry3D_Cylinder() // copy data from temp arrays std::list& vlist = ((CX3DImporter_NodeElement_Geometry3D*)ne)->Vertices;// just short alias. - for(std::vector::iterator it = tside.begin(); it != tside.end(); it++) vlist.push_back(*it); + for(std::vector::iterator it = tside.begin(); it != tside.end(); ++it) vlist.push_back(*it); if(top) { - for(std::vector::iterator it = tcir.begin(); it != tcir.end(); it++) + for(std::vector::iterator it = tcir.begin(); it != tcir.end(); ++it) { (*it).y = height;// y - because circle made in oXZ. vlist.push_back(*it); @@ -239,7 +239,7 @@ void X3DImporter::ParseNode_Geometry3D_Cylinder() if(bottom) { - for(std::vector::iterator it = tcir.begin(); it != tcir.end(); it++) + for(std::vector::iterator it = tcir.begin(); it != tcir.end(); ++it) { (*it).y = -height;// y - because circle made in oXZ. vlist.push_back(*it); @@ -336,7 +336,7 @@ void X3DImporter::ParseNode_Geometry3D_ElevationGrid() aiVector3D tvec(xSpacing * xi, *he_it, zSpacing * zi); grid_alias.Vertices.push_back(tvec); - he_it++; + ++he_it; } } }// END: create grid vertices list @@ -977,7 +977,7 @@ void X3DImporter::ParseNode_Geometry3D_Sphere() StandardShapes::MakeSphere(tess, tlist); // copy data from temp array and apply scale - for(std::vector::iterator it = tlist.begin(); it != tlist.end(); it++) + for(std::vector::iterator it = tlist.begin(); it != tlist.end(); ++it) { ((CX3DImporter_NodeElement_Geometry3D*)ne)->Vertices.push_back(*it * radius); } diff --git a/third_party/libassimp/code/X3DImporter_Group.cpp b/third_party/libassimp/code/X3D/X3DImporter_Group.cpp similarity index 99% rename from third_party/libassimp/code/X3DImporter_Group.cpp rename to third_party/libassimp/code/X3D/X3DImporter_Group.cpp index 0c2e820de8..de3610caf6 100644 --- a/third_party/libassimp/code/X3DImporter_Group.cpp +++ b/third_party/libassimp/code/X3D/X3DImporter_Group.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/X3DImporter_Light.cpp b/third_party/libassimp/code/X3D/X3DImporter_Light.cpp similarity index 99% rename from third_party/libassimp/code/X3DImporter_Light.cpp rename to third_party/libassimp/code/X3D/X3DImporter_Light.cpp index 4ffea44118..842fffc049 100644 --- a/third_party/libassimp/code/X3DImporter_Light.cpp +++ b/third_party/libassimp/code/X3D/X3DImporter_Light.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/X3DImporter_Macro.hpp b/third_party/libassimp/code/X3D/X3DImporter_Macro.hpp similarity index 99% rename from third_party/libassimp/code/X3DImporter_Macro.hpp rename to third_party/libassimp/code/X3D/X3DImporter_Macro.hpp index d1172798ce..a6aca33fb2 100644 --- a/third_party/libassimp/code/X3DImporter_Macro.hpp +++ b/third_party/libassimp/code/X3D/X3DImporter_Macro.hpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/X3DImporter_Metadata.cpp b/third_party/libassimp/code/X3D/X3DImporter_Metadata.cpp similarity index 99% rename from third_party/libassimp/code/X3DImporter_Metadata.cpp rename to third_party/libassimp/code/X3D/X3DImporter_Metadata.cpp index a566f0aa93..f888ac2b9d 100644 --- a/third_party/libassimp/code/X3DImporter_Metadata.cpp +++ b/third_party/libassimp/code/X3D/X3DImporter_Metadata.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/X3DImporter_Networking.cpp b/third_party/libassimp/code/X3D/X3DImporter_Networking.cpp similarity index 98% rename from third_party/libassimp/code/X3DImporter_Networking.cpp rename to third_party/libassimp/code/X3D/X3DImporter_Networking.cpp index 9c15c4ac42..a7a2006752 100644 --- a/third_party/libassimp/code/X3DImporter_Networking.cpp +++ b/third_party/libassimp/code/X3D/X3DImporter_Networking.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -93,7 +93,7 @@ void X3DImporter::ParseNode_Networking_Inline() // at this place new group mode created and made current, so we can name it. if(!def.empty()) NodeElement_Cur->ID = def; - if(load && (url.size() > 0)) + if(load && !url.empty()) { std::string full_path = mpIOHandler->CurrentDirectory() + url.front(); diff --git a/third_party/libassimp/code/X3DImporter_Node.hpp b/third_party/libassimp/code/X3D/X3DImporter_Node.hpp similarity index 99% rename from third_party/libassimp/code/X3DImporter_Node.hpp rename to third_party/libassimp/code/X3D/X3DImporter_Node.hpp index cb13175828..85208223dd 100644 --- a/third_party/libassimp/code/X3DImporter_Node.hpp +++ b/third_party/libassimp/code/X3D/X3DImporter_Node.hpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/X3DImporter_Postprocess.cpp b/third_party/libassimp/code/X3D/X3DImporter_Postprocess.cpp similarity index 94% rename from third_party/libassimp/code/X3DImporter_Postprocess.cpp rename to third_party/libassimp/code/X3D/X3DImporter_Postprocess.cpp index c439a40040..539563fcf0 100644 --- a/third_party/libassimp/code/X3DImporter_Postprocess.cpp +++ b/third_party/libassimp/code/X3D/X3DImporter_Postprocess.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -81,7 +81,7 @@ aiMatrix4x4 X3DImporter::PostprocessHelper_Matrix_GlobalToCurrent() const } // multiplicate all matrices in reverse order - for(std::list::reverse_iterator rit = matr.rbegin(); rit != matr.rend(); rit++) out_matr = out_matr * (*rit); + for(std::list::reverse_iterator rit = matr.rbegin(); rit != matr.rend(); ++rit) out_matr = out_matr * (*rit); return out_matr; } @@ -89,7 +89,7 @@ aiMatrix4x4 X3DImporter::PostprocessHelper_Matrix_GlobalToCurrent() const void X3DImporter::PostprocessHelper_CollectMetadata(const CX3DImporter_NodeElement& pNodeElement, std::list& pList) const { // walk through childs and find for metadata. - for(std::list::const_iterator el_it = pNodeElement.Child.begin(); el_it != pNodeElement.Child.end(); el_it++) + for(std::list::const_iterator el_it = pNodeElement.Child.begin(); el_it != pNodeElement.Child.end(); ++el_it) { if(((*el_it)->Type == CX3DImporter_NodeElement::ENET_MetaBoolean) || ((*el_it)->Type == CX3DImporter_NodeElement::ENET_MetaDouble) || ((*el_it)->Type == CX3DImporter_NodeElement::ENET_MetaFloat) || ((*el_it)->Type == CX3DImporter_NodeElement::ENET_MetaInteger) || @@ -194,7 +194,7 @@ void X3DImporter::Postprocess_BuildMaterial(const CX3DImporter_NodeElement& pNod aiMaterial& taimat = **pMaterial;// creating alias for convenience. // at this point pNodeElement point to node. Walk through childs and add all stored data. - for(std::list::const_iterator el_it = pNodeElement.Child.begin(); el_it != pNodeElement.Child.end(); el_it++) + for(std::list::const_iterator el_it = pNodeElement.Child.begin(); el_it != pNodeElement.Child.end(); ++el_it) { if((*el_it)->Type == CX3DImporter_NodeElement::ENET_Material) { @@ -255,7 +255,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle std::vector tarr; tarr.reserve(tnemesh.Vertices.size()); - for(std::list::iterator it = tnemesh.Vertices.begin(); it != tnemesh.Vertices.end(); it++) tarr.push_back(*it); + for(std::list::iterator it = tnemesh.Vertices.begin(); it != tnemesh.Vertices.end(); ++it) tarr.push_back(*it); *pMesh = StandardShapes::MakeMesh(tarr, static_cast(tnemesh.NumIndices));// create mesh from vertices using Assimp help. return;// mesh is build, nothing to do anymore. @@ -273,7 +273,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle std::vector tarr; tarr.reserve(tnemesh.Vertices.size()); - for(std::list::iterator it = tnemesh.Vertices.begin(); it != tnemesh.Vertices.end(); it++) tarr.push_back(*it); + for(std::list::iterator it = tnemesh.Vertices.begin(); it != tnemesh.Vertices.end(); ++it) tarr.push_back(*it); *pMesh = StandardShapes::MakeMesh(tarr, static_cast(tnemesh.NumIndices));// create mesh from vertices using Assimp help. @@ -289,7 +289,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle // at first create mesh from existing vertices. *pMesh = GeometryHelper_MakeMesh(tnemesh.CoordIdx, tnemesh.Vertices); // copy additional information from children - for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) { if((*ch_it)->Type == CX3DImporter_NodeElement::ENET_Color) MeshGeometry_AddColor(**pMesh, ((CX3DImporter_NodeElement_Color*)*ch_it)->Value, tnemesh.ColorPerVertex); @@ -301,7 +301,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle MeshGeometry_AddTexCoord(**pMesh, ((CX3DImporter_NodeElement_TextureCoordinate*)*ch_it)->Value); else throw DeadlyImportError("Postprocess_BuildMesh. Unknown child of ElevationGrid: " + to_string((*ch_it)->Type) + "."); - }// for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + }// for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) return;// mesh is build, nothing to do anymore. }// if(pNodeElement.Type == CX3DImporter_NodeElement::ENET_ElevationGrid) @@ -313,7 +313,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle CX3DImporter_NodeElement_IndexedSet& tnemesh = *((CX3DImporter_NodeElement_IndexedSet*)&pNodeElement);// create alias for convenience // at first search for node and create mesh. - for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) { if((*ch_it)->Type == CX3DImporter_NodeElement::ENET_Coordinate) { @@ -322,7 +322,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle } // copy additional information from children - for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) { if((*ch_it)->Type == CX3DImporter_NodeElement::ENET_Color) MeshGeometry_AddColor(**pMesh, tnemesh.CoordIndex, tnemesh.ColorIndex, ((CX3DImporter_NodeElement_Color*)*ch_it)->Value, tnemesh.ColorPerVertex); @@ -338,7 +338,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle MeshGeometry_AddTexCoord(**pMesh, tnemesh.CoordIndex, tnemesh.TexCoordIndex, ((CX3DImporter_NodeElement_TextureCoordinate*)*ch_it)->Value); else throw DeadlyImportError("Postprocess_BuildMesh. Unknown child of IndexedFaceSet: " + to_string((*ch_it)->Type) + "."); - }// for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + }// for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) return;// mesh is build, nothing to do anymore. }// if(pNodeElement.Type == CX3DImporter_NodeElement::ENET_IndexedFaceSet) @@ -348,7 +348,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle CX3DImporter_NodeElement_IndexedSet& tnemesh = *((CX3DImporter_NodeElement_IndexedSet*)&pNodeElement);// create alias for convenience // at first search for node and create mesh. - for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) { if((*ch_it)->Type == CX3DImporter_NodeElement::ENET_Coordinate) { @@ -357,7 +357,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle } // copy additional information from children - for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) { ai_assert(*pMesh); if((*ch_it)->Type == CX3DImporter_NodeElement::ENET_Color) @@ -369,7 +369,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle {} // skip because already read when mesh created. else throw DeadlyImportError("Postprocess_BuildMesh. Unknown child of IndexedLineSet: " + to_string((*ch_it)->Type) + "."); - }// for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + }// for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) return;// mesh is build, nothing to do anymore. }// if(pNodeElement.Type == CX3DImporter_NodeElement::ENET_IndexedLineSet) @@ -381,7 +381,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle CX3DImporter_NodeElement_IndexedSet& tnemesh = *((CX3DImporter_NodeElement_IndexedSet*)&pNodeElement);// create alias for convenience // at first search for node and create mesh. - for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) { if((*ch_it)->Type == CX3DImporter_NodeElement::ENET_Coordinate) { @@ -390,7 +390,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle } // copy additional information from children - for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) { ai_assert(*pMesh); if((*ch_it)->Type == CX3DImporter_NodeElement::ENET_Color) @@ -408,7 +408,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle else throw DeadlyImportError("Postprocess_BuildMesh. Unknown child of IndexedTriangleSet or IndexedTriangleFanSet, or \ IndexedTriangleStripSet: " + to_string((*ch_it)->Type) + "."); - }// for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + }// for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) return;// mesh is build, nothing to do anymore. }// if((pNodeElement.Type == CX3DImporter_NodeElement::ENET_IndexedTriangleFanSet) || (pNodeElement.Type == CX3DImporter_NodeElement::ENET_IndexedTriangleStripSet)) @@ -430,7 +430,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle CX3DImporter_NodeElement_Set& tnemesh = *((CX3DImporter_NodeElement_Set*)&pNodeElement);// create alias for convenience // at first search for node and create mesh. - for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) { if((*ch_it)->Type == CX3DImporter_NodeElement::ENET_Coordinate) { @@ -438,7 +438,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle vec_copy.reserve(((CX3DImporter_NodeElement_Coordinate*)*ch_it)->Value.size()); for(std::list::const_iterator it = ((CX3DImporter_NodeElement_Coordinate*)*ch_it)->Value.begin(); - it != ((CX3DImporter_NodeElement_Coordinate*)*ch_it)->Value.end(); it++) + it != ((CX3DImporter_NodeElement_Coordinate*)*ch_it)->Value.end(); ++it) { vec_copy.push_back(*it); } @@ -448,7 +448,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle } // copy additional information from children - for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) { ai_assert(*pMesh); if((*ch_it)->Type == CX3DImporter_NodeElement::ENET_Color) @@ -459,7 +459,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle {} // skip because already read when mesh created. else throw DeadlyImportError("Postprocess_BuildMesh. Unknown child of PointSet: " + to_string((*ch_it)->Type) + "."); - }// for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + }// for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) return;// mesh is build, nothing to do anymore. }// if(pNodeElement.Type == CX3DImporter_NodeElement::ENET_PointSet) @@ -469,7 +469,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle CX3DImporter_NodeElement_Set& tnemesh = *((CX3DImporter_NodeElement_Set*)&pNodeElement);// create alias for convenience // at first search for node and create mesh. - for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) { if((*ch_it)->Type == CX3DImporter_NodeElement::ENET_Coordinate) { @@ -478,7 +478,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle } // copy additional information from children - for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) { ai_assert(*pMesh); if((*ch_it)->Type == CX3DImporter_NodeElement::ENET_Color) @@ -489,7 +489,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle {} // skip because already read when mesh created. else throw DeadlyImportError("Postprocess_BuildMesh. Unknown child of LineSet: " + to_string((*ch_it)->Type) + "."); - }// for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + }// for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) return;// mesh is build, nothing to do anymore. }// if(pNodeElement.Type == CX3DImporter_NodeElement::ENET_LineSet) @@ -499,7 +499,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle CX3DImporter_NodeElement_Set& tnemesh = *((CX3DImporter_NodeElement_Set*)&pNodeElement);// create alias for convenience // at first search for node and create mesh. - for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) { if((*ch_it)->Type == CX3DImporter_NodeElement::ENET_Coordinate) { @@ -508,7 +508,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle } // copy additional information from children - for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) { if ( nullptr == *pMesh ) { break; @@ -526,7 +526,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle MeshGeometry_AddTexCoord(**pMesh, tnemesh.CoordIndex, tnemesh.TexCoordIndex, ((CX3DImporter_NodeElement_TextureCoordinate*)*ch_it)->Value); else throw DeadlyImportError("Postprocess_BuildMesh. Unknown child of TrianlgeFanSet: " + to_string((*ch_it)->Type) + "."); - }// for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + }// for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) return;// mesh is build, nothing to do anymore. }// if(pNodeElement.Type == CX3DImporter_NodeElement::ENET_TriangleFanSet) @@ -536,7 +536,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle CX3DImporter_NodeElement_Set& tnemesh = *((CX3DImporter_NodeElement_Set*)&pNodeElement);// create alias for convenience // at first search for node and create mesh. - for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) { if((*ch_it)->Type == CX3DImporter_NodeElement::ENET_Coordinate) { @@ -544,7 +544,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle vec_copy.reserve(((CX3DImporter_NodeElement_Coordinate*)*ch_it)->Value.size()); for(std::list::const_iterator it = ((CX3DImporter_NodeElement_Coordinate*)*ch_it)->Value.begin(); - it != ((CX3DImporter_NodeElement_Coordinate*)*ch_it)->Value.end(); it++) + it != ((CX3DImporter_NodeElement_Coordinate*)*ch_it)->Value.end(); ++it) { vec_copy.push_back(*it); } @@ -554,7 +554,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle } // copy additional information from children - for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) { ai_assert(*pMesh); if((*ch_it)->Type == CX3DImporter_NodeElement::ENET_Color) @@ -570,7 +570,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle MeshGeometry_AddTexCoord(**pMesh, tnemesh.CoordIndex, tnemesh.TexCoordIndex, ((CX3DImporter_NodeElement_TextureCoordinate*)*ch_it)->Value); else throw DeadlyImportError("Postprocess_BuildMesh. Unknown child of TrianlgeSet: " + to_string((*ch_it)->Type) + "."); - }// for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + }// for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) return;// mesh is build, nothing to do anymore. }// if(pNodeElement.Type == CX3DImporter_NodeElement::ENET_TriangleSet) @@ -580,7 +580,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle CX3DImporter_NodeElement_Set& tnemesh = *((CX3DImporter_NodeElement_Set*)&pNodeElement);// create alias for convenience // at first search for node and create mesh. - for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) { if((*ch_it)->Type == CX3DImporter_NodeElement::ENET_Coordinate) { @@ -589,7 +589,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle } // copy additional information from children - for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) { ai_assert(*pMesh); if((*ch_it)->Type == CX3DImporter_NodeElement::ENET_Color) @@ -605,7 +605,7 @@ void X3DImporter::Postprocess_BuildMesh(const CX3DImporter_NodeElement& pNodeEle MeshGeometry_AddTexCoord(**pMesh, tnemesh.CoordIndex, tnemesh.TexCoordIndex, ((CX3DImporter_NodeElement_TextureCoordinate*)*ch_it)->Value); else throw DeadlyImportError("Postprocess_BuildMesh. Unknown child of TriangleStripSet: " + to_string((*ch_it)->Type) + "."); - }// for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ch_it++) + }// for(std::list::iterator ch_it = tnemesh.Child.begin(); ch_it != tnemesh.Child.end(); ++ch_it) return;// mesh is build, nothing to do anymore. }// if(pNodeElement.Type == CX3DImporter_NodeElement::ENET_TriangleStripSet) @@ -639,16 +639,16 @@ void X3DImporter::Postprocess_BuildNode(const CX3DImporter_NodeElement& pNodeEle } else { - for(size_t i = 0; i < (size_t)tne_group.Choice; i++) chit_begin++;// forward iterator to chosen node. + for(size_t i = 0; i < (size_t)tne_group.Choice; i++) ++chit_begin;// forward iterator to chosen node. chit_end = chit_begin; - chit_end++;// point end iterator to next element after chosen node. + ++chit_end;// point end iterator to next element after chosen node. } }// if(tne_group.UseChoice) }// if(pNodeElement.Type == CX3DImporter_NodeElement::ENET_Group) // Reserve memory for fast access and check children. - for(std::list::const_iterator it = chit_begin; it != chit_end; it++) + for(std::list::const_iterator it = chit_begin; it != chit_end; ++it) {// in this loop we do not read metadata because it's already read at begin. if((*it)->Type == CX3DImporter_NodeElement::ENET_Group) { @@ -677,7 +677,7 @@ void X3DImporter::Postprocess_BuildNode(const CX3DImporter_NodeElement& pNodeEle }// for(std::list::const_iterator it = chit_begin; it != chit_end; it++) // copy data about children and meshes to aiNode. - if(SceneNode_Child.size() > 0) + if(!SceneNode_Child.empty()) { std::list::const_iterator it = SceneNode_Child.begin(); @@ -686,7 +686,7 @@ void X3DImporter::Postprocess_BuildNode(const CX3DImporter_NodeElement& pNodeEle for(size_t i = 0; i < pSceneNode.mNumChildren; i++) pSceneNode.mChildren[i] = *it++; } - if(SceneNode_Mesh.size() > 0) + if(!SceneNode_Mesh.empty()) { std::list::const_iterator it = SceneNode_Mesh.begin(); @@ -706,7 +706,7 @@ void X3DImporter::Postprocess_BuildShape(const CX3DImporter_NodeElement_Shape& p CX3DImporter_NodeElement::EType mesh_type = CX3DImporter_NodeElement::ENET_Invalid; unsigned int mat_ind = 0; - for(std::list::const_iterator it = pShapeNodeElement.Child.begin(); it != pShapeNodeElement.Child.end(); it++) + for(std::list::const_iterator it = pShapeNodeElement.Child.begin(); it != pShapeNodeElement.Child.end(); ++it) { if(PostprocessHelper_ElementIsMesh((*it)->Type)) { @@ -779,7 +779,7 @@ void X3DImporter::Postprocess_CollectMetadata(const CX3DImporter_NodeElement& pN // copy collected metadata to output node. pSceneNode.mMetaData = aiMetadata::Alloc( static_cast(meta_list.size()) ); meta_idx = 0; - for(std::list::const_iterator it = meta_list.begin(); it != meta_list.end(); it++, meta_idx++) + for(std::list::const_iterator it = meta_list.begin(); it != meta_list.end(); ++it, ++meta_idx) { CX3DImporter_NodeElement_Meta* cur_meta = (CX3DImporter_NodeElement_Meta*)*it; diff --git a/third_party/libassimp/code/X3DImporter_Rendering.cpp b/third_party/libassimp/code/X3D/X3DImporter_Rendering.cpp similarity index 99% rename from third_party/libassimp/code/X3DImporter_Rendering.cpp rename to third_party/libassimp/code/X3D/X3DImporter_Rendering.cpp index 1b44f8c19d..6e95c94417 100644 --- a/third_party/libassimp/code/X3DImporter_Rendering.cpp +++ b/third_party/libassimp/code/X3D/X3DImporter_Rendering.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -295,7 +295,7 @@ void X3DImporter::ParseNode_Rendering_IndexedTriangleFanSet() ne_alias.CoordIndex.clear(); int counter = 0; int32_t idx[3]; - for(std::vector::const_iterator idx_it = index.begin(); idx_it != index.end(); idx_it++) + for(std::vector::const_iterator idx_it = index.begin(); idx_it != index.end(); ++idx_it) { idx[2] = *idx_it; if (idx[2] < 0) @@ -413,7 +413,7 @@ void X3DImporter::ParseNode_Rendering_IndexedTriangleSet() ne_alias.CoordIndex.clear(); int counter = 0; int32_t idx[3]; - for(std::vector::const_iterator idx_it = index.begin(); idx_it != index.end(); idx_it++) + for(std::vector::const_iterator idx_it = index.begin(); idx_it != index.end(); ++idx_it) { idx[counter++] = *idx_it; if (counter > 2) @@ -519,7 +519,7 @@ void X3DImporter::ParseNode_Rendering_IndexedTriangleStripSet() ne_alias.CoordIndex.clear(); int counter = 0; int32_t idx[3]; - for(std::vector::const_iterator idx_it = index.begin(); idx_it != index.end(); idx_it++) + for(std::vector::const_iterator idx_it = index.begin(); idx_it != index.end(); ++idx_it) { idx[2] = *idx_it; if (idx[2] < 0) @@ -617,7 +617,7 @@ void X3DImporter::ParseNode_Rendering_LineSet() size_t coord_num = 0; ne_alias.CoordIndex.clear(); - for(std::vector::const_iterator vc_it = ne_alias.VertexCount.begin(); vc_it != ne_alias.VertexCount.end(); vc_it++) + for(std::vector::const_iterator vc_it = ne_alias.VertexCount.begin(); vc_it != ne_alias.VertexCount.end(); ++vc_it) { if(*vc_it < 2) throw DeadlyImportError("LineSet. vertexCount shall be greater than or equal to two."); @@ -765,7 +765,7 @@ void X3DImporter::ParseNode_Rendering_TriangleFanSet() // assign indices for first triangle coord_num_first = 0; coord_num_prev = 1; - for(std::vector::const_iterator vc_it = ne_alias.VertexCount.begin(); vc_it != ne_alias.VertexCount.end(); vc_it++) + for(std::vector::const_iterator vc_it = ne_alias.VertexCount.begin(); vc_it != ne_alias.VertexCount.end(); ++vc_it) { if(*vc_it < 3) throw DeadlyImportError("TriangleFanSet. fanCount shall be greater than or equal to three."); @@ -956,7 +956,7 @@ void X3DImporter::ParseNode_Rendering_TriangleStripSet() ne_alias.CoordIndex.clear(); coord_num_sb = 0; - for(std::vector::const_iterator vc_it = ne_alias.VertexCount.begin(); vc_it != ne_alias.VertexCount.end(); vc_it++) + for(std::vector::const_iterator vc_it = ne_alias.VertexCount.begin(); vc_it != ne_alias.VertexCount.end(); ++vc_it) { if(*vc_it < 3) throw DeadlyImportError("TriangleStripSet. stripCount shall be greater than or equal to three."); diff --git a/third_party/libassimp/code/X3DImporter_Shape.cpp b/third_party/libassimp/code/X3D/X3DImporter_Shape.cpp similarity index 99% rename from third_party/libassimp/code/X3DImporter_Shape.cpp rename to third_party/libassimp/code/X3D/X3DImporter_Shape.cpp index 43089c698d..126d5905a7 100644 --- a/third_party/libassimp/code/X3DImporter_Shape.cpp +++ b/third_party/libassimp/code/X3D/X3DImporter_Shape.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/X3DImporter_Texturing.cpp b/third_party/libassimp/code/X3D/X3DImporter_Texturing.cpp similarity index 99% rename from third_party/libassimp/code/X3DImporter_Texturing.cpp rename to third_party/libassimp/code/X3D/X3DImporter_Texturing.cpp index 807d19ff8d..2eaf3e6bc8 100644 --- a/third_party/libassimp/code/X3DImporter_Texturing.cpp +++ b/third_party/libassimp/code/X3D/X3DImporter_Texturing.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -89,7 +89,7 @@ void X3DImporter::ParseNode_Texturing_ImageTexture() ((CX3DImporter_NodeElement_ImageTexture*)ne)->RepeatS = repeatS; ((CX3DImporter_NodeElement_ImageTexture*)ne)->RepeatT = repeatT; // Attribute "url" can contain list of strings. But we need only one - first. - if(url.size() > 0) + if(!url.empty()) ((CX3DImporter_NodeElement_ImageTexture*)ne)->URL = url.front(); else ((CX3DImporter_NodeElement_ImageTexture*)ne)->URL = ""; diff --git a/third_party/libassimp/code/X3DVocabulary.cpp b/third_party/libassimp/code/X3D/X3DVocabulary.cpp similarity index 99% rename from third_party/libassimp/code/X3DVocabulary.cpp rename to third_party/libassimp/code/X3D/X3DVocabulary.cpp index dc361b7aa8..c6ee113b30 100644 --- a/third_party/libassimp/code/X3DVocabulary.cpp +++ b/third_party/libassimp/code/X3D/X3DVocabulary.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/XGLLoader.cpp b/third_party/libassimp/code/XGL/XGLLoader.cpp similarity index 98% rename from third_party/libassimp/code/XGLLoader.cpp rename to third_party/libassimp/code/XGL/XGLLoader.cpp index 0706ffd555..32cfd72ca6 100644 --- a/third_party/libassimp/code/XGLLoader.cpp +++ b/third_party/libassimp/code/XGL/XGLLoader.cpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -370,7 +370,7 @@ aiLight* XGLImporter::ReadDirectionalLight() // ------------------------------------------------------------------------------------------------ aiNode* XGLImporter::ReadObject(TempScope& scope, bool skipFirst, const char* closetag) { - std::unique_ptr nd(new aiNode()); + aiNode *nd = new aiNode; std::vector children; std::vector meshes; @@ -453,11 +453,11 @@ aiNode* XGLImporter::ReadObject(TempScope& scope, bool skipFirst, const char* cl nd->mChildren = new aiNode*[nd->mNumChildren](); for(unsigned int i = 0; i < nd->mNumChildren; ++i) { nd->mChildren[i] = children[i]; - children[i]->mParent = nd.get(); + children[i]->mParent = nd; } } - return nd.release(); + return nd; } // ------------------------------------------------------------------------------------------------ @@ -731,11 +731,10 @@ unsigned int XGLImporter::ResolveMaterialRef(TempScope& scope) } // ------------------------------------------------------------------------------------------------ -void XGLImporter::ReadMaterial(TempScope& scope) -{ +void XGLImporter::ReadMaterial(TempScope& scope) { const unsigned int mat_id = ReadIDAttr(); - std::unique_ptr mat(new aiMaterial()); + aiMaterial *mat(new aiMaterial ); while (ReadElementUpToClosing("mat")) { const std::string& s = GetElementName(); if (s == "amb") { @@ -764,11 +763,10 @@ void XGLImporter::ReadMaterial(TempScope& scope) } } - scope.materials[mat_id] = mat.get(); - scope.materials_linear.push_back(mat.release()); + scope.materials[mat_id] = mat; + scope.materials_linear.push_back(mat); } - // ---------------------------------------------------------------------------------------------- void XGLImporter::ReadFaceVertex(const TempMesh& t, TempFace& out) { diff --git a/third_party/libassimp/code/XGLLoader.h b/third_party/libassimp/code/XGL/XGLLoader.h similarity index 99% rename from third_party/libassimp/code/XGLLoader.h rename to third_party/libassimp/code/XGL/XGLLoader.h index 8ae05836a3..bba2a643cb 100644 --- a/third_party/libassimp/code/XGLLoader.h +++ b/third_party/libassimp/code/XGL/XGLLoader.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/glTFAsset.h b/third_party/libassimp/code/glTF/glTFAsset.h similarity index 95% rename from third_party/libassimp/code/glTFAsset.h rename to third_party/libassimp/code/glTF/glTFAsset.h index b046929016..ddc7f086ee 100644 --- a/third_party/libassimp/code/glTFAsset.h +++ b/third_party/libassimp/code/glTF/glTFAsset.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -52,6 +52,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_GLTF_IMPORTER +#include + #include #include #include @@ -90,38 +92,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # endif #endif +#include "glTF/glTFCommon.h" + namespace glTF { -#ifdef ASSIMP_API - using Assimp::IOStream; - using Assimp::IOSystem; - using std::shared_ptr; -#else - using std::shared_ptr; - - typedef std::runtime_error DeadlyImportError; - typedef std::runtime_error DeadlyExportError; - - enum aiOrigin { aiOrigin_SET = 0, aiOrigin_CUR = 1, aiOrigin_END = 2 }; - class IOSystem; - class IOStream - { - FILE* f; - public: - IOStream(FILE* file) : f(file) {} - ~IOStream() { fclose(f); f = 0; } - - size_t Read(void* b, size_t sz, size_t n) { return fread(b, sz, n, f); } - size_t Write(const void* b, size_t sz, size_t n) { return fwrite(b, sz, n, f); } - int Seek(size_t off, aiOrigin orig) { return fseek(f, off, int(orig)); } - size_t Tell() const { return ftell(f); } - - size_t FileSize() { - long p = Tell(), len = (Seek(0, aiOrigin_END), Tell()); - return size_t((Seek(p, aiOrigin_SET), len)); - } - }; -#endif + using glTFCommon::shared_ptr; + using glTFCommon::IOSystem; + using glTFCommon::IOStream; using rapidjson::Value; using rapidjson::Document; @@ -134,37 +111,9 @@ namespace glTF struct Light; struct Skin; - - // Vec/matrix types, as raw float arrays - typedef float (vec3)[3]; - typedef float (vec4)[4]; - typedef float (mat4)[16]; - - - namespace Util - { - void EncodeBase64(const uint8_t* in, size_t inLength, std::string& out); - - size_t DecodeBase64(const char* in, size_t inLength, uint8_t*& out); - - inline size_t DecodeBase64(const char* in, uint8_t*& out) - { - return DecodeBase64(in, strlen(in), out); - } - - struct DataURI - { - const char* mediaType; - const char* charset; - bool base64; - const char* data; - size_t dataLength; - }; - - //! Check if a uri is a data URI - inline bool ParseDataURI(const char* uri, size_t uriLen, DataURI& out); - } - + using glTFCommon::vec3; + using glTFCommon::vec4; + using glTFCommon::mat4; //! Magic number for GLB files #define AI_GLB_MAGIC_NUMBER "glTF" @@ -537,7 +486,7 @@ namespace glTF shared_ptr mData; //!< Pointer to the data bool mIsSpecial; //!< Set to true for special cases (e.g. the body buffer) - + size_t capacity = 0; //!< The capacity of the buffer in bytes. (default: 0) /// \var EncodedRegion_List /// List of encoded regions. std::list EncodedRegion_List; diff --git a/third_party/libassimp/code/glTFAsset.inl b/third_party/libassimp/code/glTF/glTFAsset.inl similarity index 88% rename from third_party/libassimp/code/glTFAsset.inl rename to third_party/libassimp/code/glTF/glTFAsset.inl index 267cbd4a39..f31781a3fc 100644 --- a/third_party/libassimp/code/glTFAsset.inl +++ b/third_party/libassimp/code/glTF/glTFAsset.inl @@ -2,8 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team - +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -52,6 +51,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endif using namespace Assimp; +using namespace glTFCommon; namespace glTF { @@ -95,6 +95,14 @@ namespace { return out.isPresent = ReadHelper::Read(val, out.value); }}; + template<> struct ReadHelper { static bool Read(Value& val, uint64_t& out) { + return val.IsUint64() ? out = val.GetUint64(), true : false; + }}; + + template<> struct ReadHelper { static bool Read(Value& val, int64_t& out) { + return val.IsInt64() ? out = val.GetInt64(), true : false; + }}; + template inline static bool ReadValue(Value& val, T& out) { @@ -293,7 +301,7 @@ inline void Buffer::Read(Value& obj, Asset& r) const char* uri = it->GetString(); - Util::DataURI dataURI; + glTFCommon::Util::DataURI dataURI; if (ParseDataURI(uri, it->GetStringLength(), dataURI)) { if (dataURI.base64) { uint8_t* data = 0; @@ -311,7 +319,7 @@ inline void Buffer::Read(Value& obj, Asset& r) " bytes, but found " + to_string(dataURI.dataLength)); } - this->mData.reset(new uint8_t[dataURI.dataLength]); + this->mData.reset(new uint8_t[dataURI.dataLength], std::default_delete()); memcpy( this->mData.get(), dataURI.data, dataURI.dataLength ); } } @@ -417,7 +425,7 @@ uint8_t* new_data; // Copy data which place after replacing part. memcpy(&new_data[pBufferData_Offset + pReplace_Count], &mData.get()[pBufferData_Offset + pBufferData_Count], pBufferData_Offset); // Apply new data - mData.reset(new_data); + mData.reset(new_data, std::default_delete()); byteLength = new_data_size; return true; @@ -434,9 +442,19 @@ inline size_t Buffer::AppendData(uint8_t* data, size_t length) inline void Buffer::Grow(size_t amount) { if (amount <= 0) return; - uint8_t* b = new uint8_t[byteLength + amount]; + if (capacity >= byteLength + amount) + { + byteLength += amount; + return; + } + + // Shift operation is standard way to divide integer by 2, it doesn't cast it to float back and forth, also works for odd numbers, + // originally it would look like: static_cast(capacity * 1.5f) + capacity = std::max(capacity + (capacity >> 1), byteLength + amount); + + uint8_t* b = new uint8_t[capacity]; if (mData) memcpy(b, mData.get(), byteLength); - mData.reset(b); + mData.reset(b, std::default_delete()); byteLength += amount; } @@ -636,12 +654,12 @@ inline void Image::Read(Value& obj, Asset& r) if (Value* uri = FindString(obj, "uri")) { const char* uristr = uri->GetString(); - Util::DataURI dataURI; + glTFCommon::Util::DataURI dataURI; if (ParseDataURI(uristr, uri->GetStringLength(), dataURI)) { mimeType = dataURI.mediaType; if (dataURI.base64) { uint8_t *ptr = nullptr; - mDataLength = Util::DecodeBase64(dataURI.data, dataURI.dataLength, ptr); + mDataLength = glTFCommon::Util::DecodeBase64(dataURI.data, dataURI.dataLength, ptr); mData.reset(ptr); } } @@ -1162,8 +1180,12 @@ inline void Light::SetDefaults() falloffExponent = 0.f; } -inline void Node::Read(Value& obj, Asset& r) -{ +inline +void Node::Read(Value& obj, Asset& r) { + if (name.empty()) { + name = id; + } + if (Value* children = FindArray(obj, "children")) { this->children.reserve(children->Size()); for (unsigned int i = 0; i < children->Size(); ++i) { @@ -1445,7 +1467,7 @@ inline std::string Asset::FindUniqueID(const std::string& str, const char* suffi if (it == mUsedIds.end()) return id; - char buffer[256]; + char buffer[1024]; int offset = ai_snprintf(buffer, sizeof(buffer), "%s_", id.c_str()); for (int i = 0; it != mUsedIds.end(); ++i) { ai_snprintf(buffer + offset, sizeof(buffer) - offset, "%d", i); @@ -1456,190 +1478,4 @@ inline std::string Asset::FindUniqueID(const std::string& str, const char* suffi return id; } -namespace Util { - - inline - bool ParseDataURI(const char* const_uri, size_t uriLen, DataURI& out) { - if ( NULL == const_uri ) { - return false; - } - - if (const_uri[0] != 0x10) { // we already parsed this uri? - if (strncmp(const_uri, "data:", 5) != 0) // not a data uri? - return false; - } - - // set defaults - out.mediaType = "text/plain"; - out.charset = "US-ASCII"; - out.base64 = false; - - char* uri = const_cast(const_uri); - if (uri[0] != 0x10) { - uri[0] = 0x10; - uri[1] = uri[2] = uri[3] = uri[4] = 0; - - size_t i = 5, j; - if (uri[i] != ';' && uri[i] != ',') { // has media type? - uri[1] = char(i); - for (; uri[i] != ';' && uri[i] != ',' && i < uriLen; ++i) { - // nothing to do! - } - } - while (uri[i] == ';' && i < uriLen) { - uri[i++] = '\0'; - for (j = i; uri[i] != ';' && uri[i] != ',' && i < uriLen; ++i) { - // nothing to do! - } - - if ( strncmp( uri + j, "charset=", 8 ) == 0 ) { - uri[2] = char(j + 8); - } else if ( strncmp( uri + j, "base64", 6 ) == 0 ) { - uri[3] = char(j); - } - } - if (i < uriLen) { - uri[i++] = '\0'; - uri[4] = char(i); - } else { - uri[1] = uri[2] = uri[3] = 0; - uri[4] = 5; - } - } - - if ( uri[ 1 ] != 0 ) { - out.mediaType = uri + uri[ 1 ]; - } - if ( uri[ 2 ] != 0 ) { - out.charset = uri + uri[ 2 ]; - } - if ( uri[ 3 ] != 0 ) { - out.base64 = true; - } - out.data = uri + uri[4]; - out.dataLength = (uri + uriLen) - out.data; - - return true; - } - - template - struct DATA - { - static const uint8_t tableDecodeBase64[128]; - }; - - template - const uint8_t DATA::tableDecodeBase64[128] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 64, 0, 0, - 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, - 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0 - }; - - inline char EncodeCharBase64(uint8_t b) - { - return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="[size_t(b)]; - } - - inline uint8_t DecodeCharBase64(char c) - { - return DATA::tableDecodeBase64[size_t(c)]; // TODO faster with lookup table or ifs? - /*if (c >= 'A' && c <= 'Z') return c - 'A'; - if (c >= 'a' && c <= 'z') return c - 'a' + 26; - if (c >= '0' && c <= '9') return c - '0' + 52; - if (c == '+') return 62; - if (c == '/') return 63; - return 64; // '-' */ - } - - inline size_t DecodeBase64(const char* in, size_t inLength, uint8_t*& out) - { - ai_assert(inLength % 4 == 0); - - if (inLength < 4) { - out = 0; - return 0; - } - - int nEquals = int(in[inLength - 1] == '=') + - int(in[inLength - 2] == '='); - - size_t outLength = (inLength * 3) / 4 - nEquals; - out = new uint8_t[outLength]; - memset(out, 0, outLength); - - size_t i, j = 0; - - for (i = 0; i + 4 < inLength; i += 4) { - uint8_t b0 = DecodeCharBase64(in[i]); - uint8_t b1 = DecodeCharBase64(in[i + 1]); - uint8_t b2 = DecodeCharBase64(in[i + 2]); - uint8_t b3 = DecodeCharBase64(in[i + 3]); - - out[j++] = (uint8_t)((b0 << 2) | (b1 >> 4)); - out[j++] = (uint8_t)((b1 << 4) | (b2 >> 2)); - out[j++] = (uint8_t)((b2 << 6) | b3); - } - - { - uint8_t b0 = DecodeCharBase64(in[i]); - uint8_t b1 = DecodeCharBase64(in[i + 1]); - uint8_t b2 = DecodeCharBase64(in[i + 2]); - uint8_t b3 = DecodeCharBase64(in[i + 3]); - - out[j++] = (uint8_t)((b0 << 2) | (b1 >> 4)); - if (b2 < 64) out[j++] = (uint8_t)((b1 << 4) | (b2 >> 2)); - if (b3 < 64) out[j++] = (uint8_t)((b2 << 6) | b3); - } - - return outLength; - } - - - - inline void EncodeBase64( - const uint8_t* in, size_t inLength, - std::string& out) - { - size_t outLength = ((inLength + 2) / 3) * 4; - - size_t j = out.size(); - out.resize(j + outLength); - - for (size_t i = 0; i < inLength; i += 3) { - uint8_t b = (in[i] & 0xFC) >> 2; - out[j++] = EncodeCharBase64(b); - - b = (in[i] & 0x03) << 4; - if (i + 1 < inLength) { - b |= (in[i + 1] & 0xF0) >> 4; - out[j++] = EncodeCharBase64(b); - - b = (in[i + 1] & 0x0F) << 2; - if (i + 2 < inLength) { - b |= (in[i + 2] & 0xC0) >> 6; - out[j++] = EncodeCharBase64(b); - - b = in[i + 2] & 0x3F; - out[j++] = EncodeCharBase64(b); - } - else { - out[j++] = EncodeCharBase64(b); - out[j++] = '='; - } - } - else { - out[j++] = EncodeCharBase64(b); - out[j++] = '='; - out[j++] = '='; - } - } - } - -} - } // ns glTF diff --git a/third_party/libassimp/code/glTFAssetWriter.h b/third_party/libassimp/code/glTF/glTFAssetWriter.h similarity index 98% rename from third_party/libassimp/code/glTFAssetWriter.h rename to third_party/libassimp/code/glTF/glTFAssetWriter.h index bbe89fc77d..03aee7d4c2 100644 --- a/third_party/libassimp/code/glTFAssetWriter.h +++ b/third_party/libassimp/code/glTF/glTFAssetWriter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/glTFAssetWriter.inl b/third_party/libassimp/code/glTF/glTFAssetWriter.inl similarity index 96% rename from third_party/libassimp/code/glTFAssetWriter.inl rename to third_party/libassimp/code/glTF/glTFAssetWriter.inl index fd29a96b4d..1bbb8fd8c2 100644 --- a/third_party/libassimp/code/glTFAssetWriter.inl +++ b/third_party/libassimp/code/glTF/glTFAssetWriter.inl @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -55,7 +55,8 @@ namespace glTF { namespace { template - inline Value& MakeValue(Value& val, float(&r)[N], MemoryPoolAllocator<>& al) { + inline + Value& MakeValue(Value& val, float(&r)[N], MemoryPoolAllocator<>& al) { val.SetArray(); val.Reserve(N, al); for (decltype(N) i = 0; i < N; ++i) { @@ -64,7 +65,8 @@ namespace glTF { return val; } - inline Value& MakeValue(Value& val, const std::vector & r, MemoryPoolAllocator<>& al) { + inline + Value& MakeValue(Value& val, const std::vector & r, MemoryPoolAllocator<>& al) { val.SetArray(); val.Reserve(static_cast(r.size()), al); for (unsigned int i = 0; i < r.size(); ++i) { @@ -213,7 +215,7 @@ namespace glTF { else if (img.HasData()) { uri = "data:" + (img.mimeType.empty() ? "application/octet-stream" : img.mimeType); uri += ";base64,"; - Util::EncodeBase64(img.GetData(), img.GetDataLength(), uri); + glTFCommon::Util::EncodeBase64(img.GetData(), img.GetDataLength(), uri); } else { uri = img.uri; @@ -294,17 +296,17 @@ namespace glTF { // filling object "compressedData" json_comp_data.SetObject(); json_comp_data.AddMember("buffer", ptr_ext_comp->Buffer, w.mAl); - json_comp_data.AddMember("byteOffset", ptr_ext_comp->Offset, w.mAl); + json_comp_data.AddMember("byteOffset", static_cast(ptr_ext_comp->Offset), w.mAl); json_comp_data.AddMember("componentType", 5121, w.mAl); json_comp_data.AddMember("type", "SCALAR", w.mAl); - json_comp_data.AddMember("count", ptr_ext_comp->Count, w.mAl); + json_comp_data.AddMember("count", static_cast(ptr_ext_comp->Count), w.mAl); if(ptr_ext_comp->Binary) json_comp_data.AddMember("mode", "binary", w.mAl); else json_comp_data.AddMember("mode", "ascii", w.mAl); - json_comp_data.AddMember("indicesCount", ptr_ext_comp->IndicesCount, w.mAl); - json_comp_data.AddMember("verticesCount", ptr_ext_comp->VerticesCount, w.mAl); + json_comp_data.AddMember("indicesCount", static_cast(ptr_ext_comp->IndicesCount), w.mAl); + json_comp_data.AddMember("verticesCount", static_cast(ptr_ext_comp->VerticesCount), w.mAl); // filling object "Open3DGC-compression" Value json_o3dgc; diff --git a/third_party/libassimp/code/glTF/glTFCommon.cpp b/third_party/libassimp/code/glTF/glTFCommon.cpp new file mode 100644 index 0000000000..cd03224e44 --- /dev/null +++ b/third_party/libassimp/code/glTF/glTFCommon.cpp @@ -0,0 +1,193 @@ +/* +Open Asset Import Library (assimp) +---------------------------------------------------------------------- + +Copyright (c) 2006-2019, 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 "glTF/glTFCommon.h" + +namespace glTFCommon { + +using namespace glTFCommon::Util; + +namespace Util { + +size_t DecodeBase64(const char* in, size_t inLength, uint8_t*& out) { + ai_assert(inLength % 4 == 0); + + if (inLength < 4) { + out = 0; + return 0; + } + + int nEquals = int(in[inLength - 1] == '=') + + int(in[inLength - 2] == '='); + + size_t outLength = (inLength * 3) / 4 - nEquals; + out = new uint8_t[outLength]; + memset(out, 0, outLength); + + size_t i, j = 0; + + for (i = 0; i + 4 < inLength; i += 4) { + uint8_t b0 = DecodeCharBase64(in[i]); + uint8_t b1 = DecodeCharBase64(in[i + 1]); + uint8_t b2 = DecodeCharBase64(in[i + 2]); + uint8_t b3 = DecodeCharBase64(in[i + 3]); + + out[j++] = (uint8_t)((b0 << 2) | (b1 >> 4)); + out[j++] = (uint8_t)((b1 << 4) | (b2 >> 2)); + out[j++] = (uint8_t)((b2 << 6) | b3); + } + + { + uint8_t b0 = DecodeCharBase64(in[i]); + uint8_t b1 = DecodeCharBase64(in[i + 1]); + uint8_t b2 = DecodeCharBase64(in[i + 2]); + uint8_t b3 = DecodeCharBase64(in[i + 3]); + + out[j++] = (uint8_t)((b0 << 2) | (b1 >> 4)); + if (b2 < 64) out[j++] = (uint8_t)((b1 << 4) | (b2 >> 2)); + if (b3 < 64) out[j++] = (uint8_t)((b2 << 6) | b3); + } + + return outLength; +} + +void EncodeBase64(const uint8_t* in, size_t inLength, std::string& out) { + size_t outLength = ((inLength + 2) / 3) * 4; + + size_t j = out.size(); + out.resize(j + outLength); + + for (size_t i = 0; i < inLength; i += 3) { + uint8_t b = (in[i] & 0xFC) >> 2; + out[j++] = EncodeCharBase64(b); + + b = (in[i] & 0x03) << 4; + if (i + 1 < inLength) { + b |= (in[i + 1] & 0xF0) >> 4; + out[j++] = EncodeCharBase64(b); + + b = (in[i + 1] & 0x0F) << 2; + if (i + 2 < inLength) { + b |= (in[i + 2] & 0xC0) >> 6; + out[j++] = EncodeCharBase64(b); + + b = in[i + 2] & 0x3F; + out[j++] = EncodeCharBase64(b); + } + else { + out[j++] = EncodeCharBase64(b); + out[j++] = '='; + } + } + else { + out[j++] = EncodeCharBase64(b); + out[j++] = '='; + out[j++] = '='; + } + } +} + +bool ParseDataURI(const char* const_uri, size_t uriLen, DataURI& out) { + if (nullptr == const_uri) { + return false; + } + + if (const_uri[0] != 0x10) { // we already parsed this uri? + if (strncmp(const_uri, "data:", 5) != 0) // not a data uri? + return false; + } + + // set defaults + out.mediaType = "text/plain"; + out.charset = "US-ASCII"; + out.base64 = false; + + char* uri = const_cast(const_uri); + if (uri[0] != 0x10) { + uri[0] = 0x10; + uri[1] = uri[2] = uri[3] = uri[4] = 0; + + size_t i = 5, j; + if (uri[i] != ';' && uri[i] != ',') { // has media type? + uri[1] = char(i); + for (; uri[i] != ';' && uri[i] != ',' && i < uriLen; ++i) { + // nothing to do! + } + } + while (uri[i] == ';' && i < uriLen) { + uri[i++] = '\0'; + for (j = i; uri[i] != ';' && uri[i] != ',' && i < uriLen; ++i) { + // nothing to do! + } + + if (strncmp(uri + j, "charset=", 8) == 0) { + uri[2] = char(j + 8); + } + else if (strncmp(uri + j, "base64", 6) == 0) { + uri[3] = char(j); + } + } + if (i < uriLen) { + uri[i++] = '\0'; + uri[4] = char(i); + } + else { + uri[1] = uri[2] = uri[3] = 0; + uri[4] = 5; + } + } + + if (uri[1] != 0) { + out.mediaType = uri + uri[1]; + } + if (uri[2] != 0) { + out.charset = uri + uri[2]; + } + if (uri[3] != 0) { + out.base64 = true; + } + out.data = uri + uri[4]; + out.dataLength = (uri + uriLen) - out.data; + + return true; +} + +} +} diff --git a/third_party/libassimp/code/glTF/glTFCommon.h b/third_party/libassimp/code/glTF/glTFCommon.h new file mode 100644 index 0000000000..d9edee75ec --- /dev/null +++ b/third_party/libassimp/code/glTF/glTFCommon.h @@ -0,0 +1,248 @@ +/* +Open Asset Import Library (assimp) +---------------------------------------------------------------------- + +Copyright (c) 2006-2019, 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. + +---------------------------------------------------------------------- +*/ +#ifndef AI_GLFTCOMMON_H_INC +#define AI_GLFTCOMMON_H_INC + +#ifndef ASSIMP_BUILD_NO_GLTF_IMPORTER + +#include + +#include +#include +#include +#include +#include +#include + +#define RAPIDJSON_HAS_STDSTRING 1 +#include +#include +#include + +#ifdef ASSIMP_API +# include +# include +# include +#else +# include +# define AI_SWAP4(p) +# define ai_assert +#endif + + +#if _MSC_VER > 1500 || (defined __GNUC___) +# define ASSIMP_GLTF_USE_UNORDERED_MULTIMAP +# else +# define gltf_unordered_map map +#endif + +#ifdef ASSIMP_GLTF_USE_UNORDERED_MULTIMAP +# include +# if _MSC_VER > 1600 +# define gltf_unordered_map unordered_map +# else +# define gltf_unordered_map tr1::unordered_map +# endif +#endif + +namespace glTFCommon { + +#ifdef ASSIMP_API + using Assimp::IOStream; + using Assimp::IOSystem; + using std::shared_ptr; +#else + using std::shared_ptr; + + typedef std::runtime_error DeadlyImportError; + typedef std::runtime_error DeadlyExportError; + + enum aiOrigin { + aiOrigin_SET = 0, + aiOrigin_CUR = 1, + aiOrigin_END = 2 + }; + + class IOSystem; + + class IOStream { + public: + IOStream(FILE* file) : f(file) {} + ~IOStream() { fclose(f); f = 0; } + + size_t Read(void* b, size_t sz, size_t n) { return fread(b, sz, n, f); } + size_t Write(const void* b, size_t sz, size_t n) { return fwrite(b, sz, n, f); } + int Seek(size_t off, aiOrigin orig) { return fseek(f, off, int(orig)); } + size_t Tell() const { return ftell(f); } + + size_t FileSize() { + long p = Tell(), len = (Seek(0, aiOrigin_END), Tell()); + return size_t((Seek(p, aiOrigin_SET), len)); + } + + private: + FILE* f; + }; +#endif + + // Vec/matrix types, as raw float arrays + typedef float(vec3)[3]; + typedef float(vec4)[4]; + typedef float(mat4)[16]; + + inline + void CopyValue(const glTFCommon::vec3& v, aiColor4D& out) { + out.r = v[0]; + out.g = v[1]; + out.b = v[2]; + out.a = 1.0; + } + + inline + void CopyValue(const glTFCommon::vec4& v, aiColor4D& out) { + out.r = v[0]; + out.g = v[1]; + out.b = v[2]; + out.a = v[3]; + } + + inline + void CopyValue(const glTFCommon::vec4& v, aiColor3D& out) { + out.r = v[0]; + out.g = v[1]; + out.b = v[2]; + } + + inline + void CopyValue(const glTFCommon::vec3& v, aiColor3D& out) { + out.r = v[0]; + out.g = v[1]; + out.b = v[2]; + } + + inline + void CopyValue(const glTFCommon::vec3& v, aiVector3D& out) { + out.x = v[0]; + out.y = v[1]; + out.z = v[2]; + } + + inline + void CopyValue(const glTFCommon::vec4& v, aiQuaternion& out) { + out.x = v[0]; + out.y = v[1]; + out.z = v[2]; + out.w = v[3]; + } + + inline + void CopyValue(const glTFCommon::mat4& v, aiMatrix4x4& o) { + o.a1 = v[0]; o.b1 = v[1]; o.c1 = v[2]; o.d1 = v[3]; + o.a2 = v[4]; o.b2 = v[5]; o.c2 = v[6]; o.d2 = v[7]; + o.a3 = v[8]; o.b3 = v[9]; o.c3 = v[10]; o.d3 = v[11]; + o.a4 = v[12]; o.b4 = v[13]; o.c4 = v[14]; o.d4 = v[15]; + } + + namespace Util { + + void EncodeBase64(const uint8_t* in, size_t inLength, std::string& out); + + size_t DecodeBase64(const char* in, size_t inLength, uint8_t*& out); + + inline + size_t DecodeBase64(const char* in, uint8_t*& out) { + return DecodeBase64(in, strlen(in), out); + } + + struct DataURI { + const char* mediaType; + const char* charset; + bool base64; + const char* data; + size_t dataLength; + }; + + //! Check if a uri is a data URI + bool ParseDataURI(const char* const_uri, size_t uriLen, DataURI& out); + + template + struct DATA { + static const uint8_t tableDecodeBase64[128]; + }; + + template + const uint8_t DATA::tableDecodeBase64[128] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 64, 0, 0, + 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, + 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0 + }; + + inline + char EncodeCharBase64(uint8_t b) { + return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="[size_t(b)]; + } + + inline + uint8_t DecodeCharBase64(char c) { + return DATA::tableDecodeBase64[size_t(c)]; // TODO faster with lookup table or ifs? + /*if (c >= 'A' && c <= 'Z') return c - 'A'; + if (c >= 'a' && c <= 'z') return c - 'a' + 26; + if (c >= '0' && c <= '9') return c - '0' + 52; + if (c == '+') return 62; + if (c == '/') return 63; + return 64; // '-' */ + } + + size_t DecodeBase64(const char* in, size_t inLength, uint8_t*& out); + + void EncodeBase64(const uint8_t* in, size_t inLength, std::string& out); + } + +} + +#endif // ASSIMP_BUILD_NO_GLTF_IMPORTER + +#endif // AI_GLFTCOMMON_H_INC diff --git a/third_party/libassimp/code/glTFExporter.cpp b/third_party/libassimp/code/glTF/glTFExporter.cpp similarity index 98% rename from third_party/libassimp/code/glTFExporter.cpp rename to third_party/libassimp/code/glTF/glTFExporter.cpp index 29a88af8ba..034f91f3be 100644 --- a/third_party/libassimp/code/glTFExporter.cpp +++ b/third_party/libassimp/code/glTF/glTFExporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -42,14 +42,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_EXPORT #ifndef ASSIMP_BUILD_NO_GLTF_EXPORTER -#include "glTFExporter.h" +#include "glTF/glTFExporter.h" +#include "glTF/glTFAssetWriter.h" +#include "PostProcessing/SplitLargeMeshes.h" #include #include #include - -#include "SplitLargeMeshes.h" - #include #include #include @@ -61,8 +60,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include "glTFAssetWriter.h" - #ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC // Header files, Open3DGC. # include @@ -101,17 +98,17 @@ glTFExporter::glTFExporter(const char* filename, IOSystem* pIOSystem, const aiSc { aiScene* sceneCopy_tmp; SceneCombiner::CopyScene(&sceneCopy_tmp, pScene); - std::unique_ptr sceneCopy(sceneCopy_tmp); + aiScene *sceneCopy(sceneCopy_tmp); SplitLargeMeshesProcess_Triangle tri_splitter; tri_splitter.SetLimit(0xffff); - tri_splitter.Execute(sceneCopy.get()); + tri_splitter.Execute(sceneCopy); SplitLargeMeshesProcess_Vertex vert_splitter; vert_splitter.SetLimit(0xffff); - vert_splitter.Execute(sceneCopy.get()); + vert_splitter.Execute(sceneCopy); - mScene = sceneCopy.get(); + mScene = sceneCopy; mAsset.reset( new glTF::Asset( pIOSystem ) ); @@ -245,7 +242,10 @@ inline Ref ExportData(Asset& a, std::string& meshName, Ref& bu namespace { void GetMatScalar(const aiMaterial* mat, float& val, const char* propName, int type, int idx) { - if (mat->Get(propName, type, idx, val) == AI_SUCCESS) {} + ai_assert( nullptr != mat ); + if ( nullptr != mat ) { + mat->Get(propName, type, idx, val); + } } } diff --git a/third_party/libassimp/code/glTFExporter.h b/third_party/libassimp/code/glTF/glTFExporter.h similarity index 99% rename from third_party/libassimp/code/glTFExporter.h rename to third_party/libassimp/code/glTF/glTFExporter.h index 061dac5e88..d6c2e7f04e 100644 --- a/third_party/libassimp/code/glTFExporter.h +++ b/third_party/libassimp/code/glTF/glTFExporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/glTFImporter.cpp b/third_party/libassimp/code/glTF/glTFImporter.cpp old mode 100755 new mode 100644 similarity index 92% rename from third_party/libassimp/code/glTFImporter.cpp rename to third_party/libassimp/code/glTF/glTFImporter.cpp index c68969dc62..9ecd742f60 --- a/third_party/libassimp/code/glTFImporter.cpp +++ b/third_party/libassimp/code/glTF/glTFImporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -42,10 +42,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_GLTF_IMPORTER -#include "glTFImporter.h" +#include "glTF/glTFImporter.h" +#include "glTF/glTFAsset.h" +#include "glTF/glTFAssetWriter.h" +#include "PostProcessing/MakeVerboseFormat.h" + #include #include - #include #include #include @@ -54,16 +57,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include -#include "MakeVerboseFormat.h" - -#include "glTFAsset.h" -// This is included here so WriteLazyDict's definition is found. -#include "glTFAssetWriter.h" - using namespace Assimp; using namespace glTF; - // // glTFImporter // @@ -86,7 +82,7 @@ glTFImporter::glTFImporter() : BaseImporter() , meshOffsets() , embeddedTexIdxs() -, mScene( NULL ) { +, mScene( nullptr ) { // empty } @@ -94,17 +90,16 @@ glTFImporter::~glTFImporter() { // empty } -const aiImporterDesc* glTFImporter::GetInfo() const -{ +const aiImporterDesc* glTFImporter::GetInfo() const { return &desc; } -bool glTFImporter::CanRead(const std::string& pFile, IOSystem* pIOHandler, bool /* checkSig */) const -{ +bool glTFImporter::CanRead(const std::string& pFile, IOSystem* pIOHandler, bool /* checkSig */) const { const std::string &extension = GetExtension(pFile); - if (extension != "gltf" && extension != "glb") + if (extension != "gltf" && extension != "glb") { return false; + } if (pIOHandler) { glTF::Asset asset(pIOHandler); @@ -120,44 +115,9 @@ bool glTFImporter::CanRead(const std::string& pFile, IOSystem* pIOHandler, bool return false; } - - -//static void CopyValue(const glTF::vec3& v, aiColor3D& out) -//{ -// out.r = v[0]; out.g = v[1]; out.b = v[2]; -//} - -static void CopyValue(const glTF::vec4& v, aiColor4D& out) -{ - out.r = v[0]; out.g = v[1]; out.b = v[2]; out.a = v[3]; -} - -static void CopyValue(const glTF::vec4& v, aiColor3D& out) -{ - out.r = v[0]; out.g = v[1]; out.b = v[2]; -} - -static void CopyValue(const glTF::vec3& v, aiVector3D& out) -{ - out.x = v[0]; out.y = v[1]; out.z = v[2]; -} - -static void CopyValue(const glTF::vec4& v, aiQuaternion& out) -{ - out.x = v[0]; out.y = v[1]; out.z = v[2]; out.w = v[3]; -} - -static void CopyValue(const glTF::mat4& v, aiMatrix4x4& o) -{ - o.a1 = v[ 0]; o.b1 = v[ 1]; o.c1 = v[ 2]; o.d1 = v[ 3]; - o.a2 = v[ 4]; o.b2 = v[ 5]; o.c2 = v[ 6]; o.d2 = v[ 7]; - o.a3 = v[ 8]; o.b3 = v[ 9]; o.c3 = v[10]; o.d3 = v[11]; - o.a4 = v[12]; o.b4 = v[13]; o.c4 = v[14]; o.d4 = v[15]; -} - -inline void SetMaterialColorProperty(std::vector& embeddedTexIdxs, Asset& /*r*/, glTF::TexProperty prop, aiMaterial* mat, - aiTextureType texType, const char* pKey, unsigned int type, unsigned int idx) -{ +inline +void SetMaterialColorProperty(std::vector& embeddedTexIdxs, Asset& /*r*/, glTF::TexProperty prop, aiMaterial* mat, + aiTextureType texType, const char* pKey, unsigned int type, unsigned int idx) { if (prop.texture) { if (prop.texture->source) { aiString uri(prop.texture->source->uri); @@ -171,16 +131,14 @@ inline void SetMaterialColorProperty(std::vector& embeddedTexIdxs, Asset& / mat->AddProperty(&uri, _AI_MATKEY_TEXTURE_BASE, texType, 0); } - } - else { + } else { aiColor4D col; CopyValue(prop.color, col); mat->AddProperty(&col, 1, pKey, type, idx); } } -void glTFImporter::ImportMaterials(glTF::Asset& r) -{ +void glTFImporter::ImportMaterials(glTF::Asset& r) { mScene->mNumMaterials = unsigned(r.materials.Size()); mScene->mMaterials = new aiMaterial*[mScene->mNumMaterials]; @@ -308,7 +266,7 @@ void glTFImporter::ImportMeshes(glTF::Asset& r) aim->mName = mesh.id; if (mesh.primitives.size() > 1) { - size_t& len = aim->mName.length; + ai_uint32& len = aim->mName.length; aim->mName.data[len] = '-'; len += 1 + ASSIMP_itoa10(aim->mName.data + len + 1, unsigned(MAXLEN - len - 1), p); } @@ -503,27 +461,31 @@ void glTFImporter::ImportMeshes(glTF::Asset& r) CopyVector(meshes, mScene->mMeshes, mScene->mNumMeshes); } -void glTFImporter::ImportCameras(glTF::Asset& r) -{ - if (!r.cameras.Size()) return; +void glTFImporter::ImportCameras(glTF::Asset& r) { + if (!r.cameras.Size()) { + return; + } mScene->mNumCameras = r.cameras.Size(); mScene->mCameras = new aiCamera*[r.cameras.Size()]; - for (size_t i = 0; i < r.cameras.Size(); ++i) { Camera& cam = r.cameras[i]; aiCamera* aicam = mScene->mCameras[i] = new aiCamera(); if (cam.type == Camera::Perspective) { - aicam->mAspect = cam.perspective.aspectRatio; - aicam->mHorizontalFOV = cam.perspective.yfov * aicam->mAspect; + aicam->mHorizontalFOV = cam.perspective.yfov * ((aicam->mAspect == 0.f) ? 1.f : aicam->mAspect); aicam->mClipPlaneFar = cam.perspective.zfar; aicam->mClipPlaneNear = cam.perspective.znear; - } - else { - // assimp does not support orthographic cameras + } else { + aicam->mClipPlaneFar = cam.ortographic.zfar; + aicam->mClipPlaneNear = cam.ortographic.znear; + aicam->mHorizontalFOV = 0.0; + aicam->mAspect = 1.0f; + if (0.f != cam.ortographic.ymag) { + aicam->mAspect = cam.ortographic.xmag / cam.ortographic.ymag; + } } } } @@ -717,7 +679,11 @@ void glTFImporter::ImportEmbeddedTextures(glTF::Asset& r) } } -void glTFImporter::InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) { +void glTFImporter::InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) +{ + // clean all member arrays + meshOffsets.clear(); + embeddedTexIdxs.clear(); this->mScene = pScene; diff --git a/third_party/libassimp/code/glTFImporter.h b/third_party/libassimp/code/glTF/glTFImporter.h similarity index 98% rename from third_party/libassimp/code/glTFImporter.h rename to third_party/libassimp/code/glTF/glTFImporter.h index 064d6dc1ab..ce8a000dc4 100644 --- a/third_party/libassimp/code/glTFImporter.h +++ b/third_party/libassimp/code/glTF/glTFImporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/glTF2Asset.h b/third_party/libassimp/code/glTF2/glTF2Asset.h similarity index 94% rename from third_party/libassimp/code/glTF2Asset.h rename to third_party/libassimp/code/glTF2/glTF2Asset.h index 92be82f3b9..15c4c44fa0 100644 --- a/third_party/libassimp/code/glTF2Asset.h +++ b/third_party/libassimp/code/glTF2/glTF2Asset.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -46,12 +46,15 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * glTF Extensions Support: * KHR_materials_pbrSpecularGlossiness full * KHR_materials_unlit full + * KHR_lights_punctual full */ #ifndef GLTF2ASSET_H_INC #define GLTF2ASSET_H_INC #ifndef ASSIMP_BUILD_NO_GLTF_IMPORTER +#include + #include #include #include @@ -92,38 +95,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include +#include "glTF/glTFCommon.h" + namespace glTF2 { -#ifdef ASSIMP_API - using Assimp::IOStream; - using Assimp::IOSystem; - using std::shared_ptr; -#else - using std::shared_ptr; - - typedef std::runtime_error DeadlyImportError; - typedef std::runtime_error DeadlyExportError; - - enum aiOrigin { aiOrigin_SET = 0, aiOrigin_CUR = 1, aiOrigin_END = 2 }; - class IOSystem; - class IOStream - { - FILE* f; - public: - IOStream(FILE* file) : f(file) {} - ~IOStream() { fclose(f); f = 0; } - - size_t Read(void* b, size_t sz, size_t n) { return fread(b, sz, n, f); } - size_t Write(const void* b, size_t sz, size_t n) { return fwrite(b, sz, n, f); } - int Seek(size_t off, aiOrigin orig) { return fseek(f, off, int(orig)); } - size_t Tell() const { return ftell(f); } - - size_t FileSize() { - long p = Tell(), len = (Seek(0, aiOrigin_END), Tell()); - return size_t((Seek(p, aiOrigin_SET), len)); - } - }; -#endif + using glTFCommon::shared_ptr; + using glTFCommon::IOSystem; + using glTFCommon::IOStream; using rapidjson::Value; using rapidjson::Document; @@ -135,35 +113,9 @@ namespace glTF2 struct Texture; struct Skin; - // Vec/matrix types, as raw float arrays - typedef float (vec3)[3]; - typedef float (vec4)[4]; - typedef float (mat4)[16]; - - namespace Util - { - void EncodeBase64(const uint8_t* in, size_t inLength, std::string& out); - - size_t DecodeBase64(const char* in, size_t inLength, uint8_t*& out); - - inline size_t DecodeBase64(const char* in, uint8_t*& out) - { - return DecodeBase64(in, strlen(in), out); - } - - struct DataURI - { - const char* mediaType; - const char* charset; - bool base64; - const char* data; - size_t dataLength; - }; - - //! Check if a uri is a data URI - inline bool ParseDataURI(const char* uri, size_t uriLen, DataURI& out); - } - + using glTFCommon::vec3; + using glTFCommon::vec4; + using glTFCommon::mat4; //! Magic number for GLB files #define AI_GLB_MAGIC_NUMBER "glTF" @@ -223,7 +175,8 @@ namespace glTF2 ComponentType_FLOAT = 5126 }; - inline unsigned int ComponentTypeSize(ComponentType t) + inline + unsigned int ComponentTypeSize(ComponentType t) { switch (t) { case ComponentType_SHORT: @@ -250,7 +203,7 @@ namespace glTF2 }; //! Values for the Sampler::magFilter field - enum class SamplerMagFilter: unsigned int + enum class SamplerMagFilter : unsigned int { UNSET = 0, SamplerMagFilter_Nearest = 9728, @@ -258,7 +211,7 @@ namespace glTF2 }; //! Values for the Sampler::minFilter field - enum class SamplerMinFilter: unsigned int + enum class SamplerMinFilter : unsigned int { UNSET = 0, SamplerMinFilter_Nearest = 9728, @@ -430,9 +383,9 @@ namespace glTF2 struct Accessor : public Object { Ref bufferView; //!< The ID of the bufferView. (required) - unsigned int byteOffset; //!< The offset relative to the start of the bufferView in bytes. (required) + size_t byteOffset; //!< The offset relative to the start of the bufferView in bytes. (required) ComponentType componentType; //!< The datatype of components in the attribute. (required) - unsigned int count; //!< The number of attributes referenced by this accessor. (required) + size_t count; //!< The number of attributes referenced by this accessor. (required) AttribType::Value type; //!< Specifies if the attribute is a scalar, vector, or matrix. (required) std::vector max; //!< Maximum value of each component in this attribute. std::vector min; //!< Minimum value of each component in this attribute. @@ -529,6 +482,7 @@ namespace glTF2 //std::string uri; //!< The uri of the buffer. Can be a filepath, a data uri, etc. (required) size_t byteLength; //!< The length of the buffer in bytes. (default: 0) //std::string type; //!< XMLHttpRequest responseType (default: "arraybuffer") + size_t capacity = 0; //!< The capacity of the buffer in bytes. (default: 0) Type type; @@ -547,7 +501,7 @@ namespace glTF2 /// but in real life you'll get: /// "accessor_0" : { byteOffset: 0, byteLength: 4}, "accessor_1" : { byteOffset: 2, byteLength: 4} /// Yes, accessor of next mesh has offset and length which mean: current mesh data is decoded, all other data is encoded. - /// And when before you start to read data of current mesh (with encoded data ofcourse) you must decode region of "bufferView", after read finished + /// And when before you start to read data of current mesh (with encoded data of course) you must decode region of "bufferView", after read finished /// delete encoding mark. And after that you can repeat process: decode data of mesh, read, delete decoded data. /// /// Remark. Encoding all data at once is good in world with computers which do not has RAM limitation. So, you must use step by step encoding in @@ -656,10 +610,36 @@ namespace glTF2 } ortographic; } cameraProperties; - Camera() {} + Camera() + : type(Perspective) + , cameraProperties() { + // empty + } void Read(Value& obj, Asset& r); }; + //! A light (from KHR_lights_punctual extension) + struct Light : public Object + { + enum Type + { + Directional, + Point, + Spot + }; + + Type type; + + vec3 color; + float intensity; + Nullable range; + + float innerConeAngle; + float outerConeAngle; + + Light() {} + void Read(Value& obj, Asset& r); + }; //! Image data used to create a texture. struct Image : public Object @@ -811,6 +791,7 @@ namespace glTF2 Nullable scale; Ref camera; + Ref light; std::vector< Ref > skeletons; //!< The ID of skeleton nodes. Each of which is the root of a node hierarchy. Ref skin; //!< The ID of the skin referenced by this node. @@ -1042,6 +1023,7 @@ namespace glTF2 { bool KHR_materials_pbrSpecularGlossiness; bool KHR_materials_unlit; + bool KHR_lights_punctual; } extensionsUsed; @@ -1055,6 +1037,7 @@ namespace glTF2 LazyDict buffers; LazyDict bufferViews; LazyDict cameras; + LazyDict lights; LazyDict images; LazyDict materials; LazyDict meshes; @@ -1075,6 +1058,7 @@ namespace glTF2 , buffers (*this, "buffers") , bufferViews (*this, "bufferViews") , cameras (*this, "cameras") + , lights (*this, "lights", "KHR_lights_punctual") , images (*this, "images") , materials (*this, "materials") , meshes (*this, "meshes") diff --git a/third_party/libassimp/code/glTF2Asset.inl b/third_party/libassimp/code/glTF2/glTF2Asset.inl old mode 100755 new mode 100644 similarity index 87% rename from third_party/libassimp/code/glTF2Asset.inl rename to third_party/libassimp/code/glTF2/glTF2Asset.inl index ed37937f41..6b47b16070 --- a/third_party/libassimp/code/glTF2Asset.inl +++ b/third_party/libassimp/code/glTF2/glTF2Asset.inl @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -85,6 +85,14 @@ namespace { return val.IsString() ? (out = std::string(val.GetString(), val.GetStringLength()), true) : false; }}; + template<> struct ReadHelper { static bool Read(Value& val, uint64_t& out) { + return val.IsUint64() ? out = val.GetUint64(), true : false; + }}; + + template<> struct ReadHelper { static bool Read(Value& val, int64_t& out) { + return val.IsInt64() ? out = val.GetInt64(), true : false; + }}; + template struct ReadHelper< Nullable > { static bool Read(Value& val, Nullable& out) { return out.isPresent = ReadHelper::Read(val, out.value); }}; @@ -274,9 +282,7 @@ Ref LazyDict::Retrieve(unsigned int i) template Ref LazyDict::Get(unsigned int i) { - return Ref(mObjs, i); - } template @@ -353,11 +359,11 @@ inline void Buffer::Read(Value& obj, Asset& r) const char* uri = it->GetString(); - Util::DataURI dataURI; + glTFCommon::Util::DataURI dataURI; if (ParseDataURI(uri, it->GetStringLength(), dataURI)) { if (dataURI.base64) { uint8_t* data = 0; - this->byteLength = Util::DecodeBase64(dataURI.data, dataURI.dataLength, data); + this->byteLength = glTFCommon::Util::DecodeBase64(dataURI.data, dataURI.dataLength, data); this->mData.reset(data, std::default_delete()); if (statedLength > 0 && this->byteLength != statedLength) { @@ -520,7 +526,17 @@ inline size_t Buffer::AppendData(uint8_t* data, size_t length) inline void Buffer::Grow(size_t amount) { if (amount <= 0) return; - uint8_t* b = new uint8_t[byteLength + amount]; + if (capacity >= byteLength + amount) + { + byteLength += amount; + return; + } + + // Shift operation is standard way to divide integer by 2, it doesn't cast it to float back and forth, also works for odd numbers, + // originally it would look like: static_cast(capacity * 1.5f) + capacity = std::max(capacity + (capacity >> 1), byteLength + amount); + + uint8_t* b = new uint8_t[capacity]; if (mData) memcpy(b, mData.get(), byteLength); mData.reset(b, std::default_delete()); byteLength += amount; @@ -537,8 +553,8 @@ inline void BufferView::Read(Value& obj, Asset& r) buffer = r.buffers.Retrieve(bufferVal->GetUint()); } - byteOffset = MemberOrDefault(obj, "byteOffset", 0u); - byteLength = MemberOrDefault(obj, "byteLength", 0u); + byteOffset = MemberOrDefault(obj, "byteOffset", size_t(0)); + byteLength = MemberOrDefault(obj, "byteLength", size_t(0)); byteStride = MemberOrDefault(obj, "byteStride", 0u); } @@ -553,9 +569,9 @@ inline void Accessor::Read(Value& obj, Asset& r) bufferView = r.bufferViews.Retrieve(bufferViewVal->GetUint()); } - byteOffset = MemberOrDefault(obj, "byteOffset", 0u); + byteOffset = MemberOrDefault(obj, "byteOffset", size_t(0)); componentType = MemberOrDefault(obj, "componentType", ComponentType_BYTE); - count = MemberOrDefault(obj, "count", 0u); + count = MemberOrDefault(obj, "count", size_t(0)); const char* typestr; type = ReadMember(obj, "type", typestr) ? AttribType::FromString(typestr) : AttribType::SCALAR; @@ -699,12 +715,12 @@ inline void Image::Read(Value& obj, Asset& r) if (Value* uri = FindString(obj, "uri")) { const char* uristr = uri->GetString(); - Util::DataURI dataURI; + glTFCommon::Util::DataURI dataURI; if (ParseDataURI(uristr, uri->GetStringLength(), dataURI)) { mimeType = dataURI.mediaType; if (dataURI.base64) { uint8_t *ptr = nullptr; - mDataLength = Util::DecodeBase64(dataURI.data, dataURI.dataLength, ptr); + mDataLength = glTFCommon::Util::DecodeBase64(dataURI.data, dataURI.dataLength, ptr); mData.reset(ptr); } } @@ -1049,8 +1065,44 @@ inline void Camera::Read(Value& obj, Asset& /*r*/) } } -inline void Node::Read(Value& obj, Asset& r) +inline void Light::Read(Value& obj, Asset& /*r*/) { +#ifndef M_PI + const float M_PI = 3.14159265358979323846f; +#endif + + std::string type_string; + ReadMember(obj, "type", type_string); + if (type_string == "directional") + type = Light::Directional; + else if (type_string == "point") + type = Light::Point; + else + type = Light::Spot; + + name = MemberOrDefault(obj, "name", ""); + + SetVector(color, vec3{ 1.0f, 1.0f, 1.0f }); + ReadMember(obj, "color", color); + + intensity = MemberOrDefault(obj, "intensity", 1.0f); + + ReadMember(obj, "range", range); + + if (type == Light::Spot) + { + Value* spot = FindObject(obj, "spot"); + if (!spot) throw DeadlyImportError("GLTF: Light missing its spot parameters"); + innerConeAngle = MemberOrDefault(*spot, "innerConeAngle", 0.0f); + outerConeAngle = MemberOrDefault(*spot, "outerConeAngle", M_PI / 4.0f); + } +} + +inline +void Node::Read(Value& obj, Asset& r) { + if (name.empty()) { + name = id; + } if (Value* children = FindArray(obj, "children")) { this->children.reserve(children->Size()); @@ -1092,6 +1144,19 @@ inline void Node::Read(Value& obj, Asset& r) if (this->camera) this->camera->id = this->id; } + + if (Value* extensions = FindObject(obj, "extensions")) { + if (r.extensionsUsed.KHR_lights_punctual) { + + if (Value* ext = FindObject(*extensions, "KHR_lights_punctual")) { + if (Value* light = FindUInt(*ext, "light")) { + this->light = r.lights.Retrieve(light->GetUint()); + if (this->light) + this->light->id = this->id; + } + } + } + } } inline void Scene::Read(Value& obj, Asset& r) @@ -1403,6 +1468,7 @@ inline void Asset::ReadExtensionsUsed(Document& doc) CHECK_EXT(KHR_materials_pbrSpecularGlossiness); CHECK_EXT(KHR_materials_unlit); + CHECK_EXT(KHR_lights_punctual); #undef CHECK_EXT } @@ -1450,190 +1516,4 @@ inline std::string Asset::FindUniqueID(const std::string& str, const char* suffi return id; } -namespace Util { - - inline - bool ParseDataURI(const char* const_uri, size_t uriLen, DataURI& out) { - if ( NULL == const_uri ) { - return false; - } - - if (const_uri[0] != 0x10) { // we already parsed this uri? - if (strncmp(const_uri, "data:", 5) != 0) // not a data uri? - return false; - } - - // set defaults - out.mediaType = "text/plain"; - out.charset = "US-ASCII"; - out.base64 = false; - - char* uri = const_cast(const_uri); - if (uri[0] != 0x10) { - uri[0] = 0x10; - uri[1] = uri[2] = uri[3] = uri[4] = 0; - - size_t i = 5, j; - if (uri[i] != ';' && uri[i] != ',') { // has media type? - uri[1] = char(i); - for (; uri[i] != ';' && uri[i] != ',' && i < uriLen; ++i) { - // nothing to do! - } - } - while (uri[i] == ';' && i < uriLen) { - uri[i++] = '\0'; - for (j = i; uri[i] != ';' && uri[i] != ',' && i < uriLen; ++i) { - // nothing to do! - } - - if ( strncmp( uri + j, "charset=", 8 ) == 0 ) { - uri[2] = char(j + 8); - } else if ( strncmp( uri + j, "base64", 6 ) == 0 ) { - uri[3] = char(j); - } - } - if (i < uriLen) { - uri[i++] = '\0'; - uri[4] = char(i); - } else { - uri[1] = uri[2] = uri[3] = 0; - uri[4] = 5; - } - } - - if ( uri[ 1 ] != 0 ) { - out.mediaType = uri + uri[ 1 ]; - } - if ( uri[ 2 ] != 0 ) { - out.charset = uri + uri[ 2 ]; - } - if ( uri[ 3 ] != 0 ) { - out.base64 = true; - } - out.data = uri + uri[4]; - out.dataLength = (uri + uriLen) - out.data; - - return true; - } - - template - struct DATA - { - static const uint8_t tableDecodeBase64[128]; - }; - - template - const uint8_t DATA::tableDecodeBase64[128] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 64, 0, 0, - 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, - 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0 - }; - - inline char EncodeCharBase64(uint8_t b) - { - return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="[size_t(b)]; - } - - inline uint8_t DecodeCharBase64(char c) - { - return DATA::tableDecodeBase64[size_t(c)]; // TODO faster with lookup table or ifs? - /*if (c >= 'A' && c <= 'Z') return c - 'A'; - if (c >= 'a' && c <= 'z') return c - 'a' + 26; - if (c >= '0' && c <= '9') return c - '0' + 52; - if (c == '+') return 62; - if (c == '/') return 63; - return 64; // '-' */ - } - - inline size_t DecodeBase64(const char* in, size_t inLength, uint8_t*& out) - { - ai_assert(inLength % 4 == 0); - - if (inLength < 4) { - out = 0; - return 0; - } - - int nEquals = int(in[inLength - 1] == '=') + - int(in[inLength - 2] == '='); - - size_t outLength = (inLength * 3) / 4 - nEquals; - out = new uint8_t[outLength]; - memset(out, 0, outLength); - - size_t i, j = 0; - - for (i = 0; i + 4 < inLength; i += 4) { - uint8_t b0 = DecodeCharBase64(in[i]); - uint8_t b1 = DecodeCharBase64(in[i + 1]); - uint8_t b2 = DecodeCharBase64(in[i + 2]); - uint8_t b3 = DecodeCharBase64(in[i + 3]); - - out[j++] = (uint8_t)((b0 << 2) | (b1 >> 4)); - out[j++] = (uint8_t)((b1 << 4) | (b2 >> 2)); - out[j++] = (uint8_t)((b2 << 6) | b3); - } - - { - uint8_t b0 = DecodeCharBase64(in[i]); - uint8_t b1 = DecodeCharBase64(in[i + 1]); - uint8_t b2 = DecodeCharBase64(in[i + 2]); - uint8_t b3 = DecodeCharBase64(in[i + 3]); - - out[j++] = (uint8_t)((b0 << 2) | (b1 >> 4)); - if (b2 < 64) out[j++] = (uint8_t)((b1 << 4) | (b2 >> 2)); - if (b3 < 64) out[j++] = (uint8_t)((b2 << 6) | b3); - } - - return outLength; - } - - - - inline void EncodeBase64( - const uint8_t* in, size_t inLength, - std::string& out) - { - size_t outLength = ((inLength + 2) / 3) * 4; - - size_t j = out.size(); - out.resize(j + outLength); - - for (size_t i = 0; i < inLength; i += 3) { - uint8_t b = (in[i] & 0xFC) >> 2; - out[j++] = EncodeCharBase64(b); - - b = (in[i] & 0x03) << 4; - if (i + 1 < inLength) { - b |= (in[i + 1] & 0xF0) >> 4; - out[j++] = EncodeCharBase64(b); - - b = (in[i + 1] & 0x0F) << 2; - if (i + 2 < inLength) { - b |= (in[i + 2] & 0xC0) >> 6; - out[j++] = EncodeCharBase64(b); - - b = in[i + 2] & 0x3F; - out[j++] = EncodeCharBase64(b); - } - else { - out[j++] = EncodeCharBase64(b); - out[j++] = '='; - } - } - else { - out[j++] = EncodeCharBase64(b); - out[j++] = '='; - out[j++] = '='; - } - } - } - -} - } // ns glTF diff --git a/third_party/libassimp/code/glTF2AssetWriter.h b/third_party/libassimp/code/glTF2/glTF2AssetWriter.h similarity index 98% rename from third_party/libassimp/code/glTF2AssetWriter.h rename to third_party/libassimp/code/glTF2/glTF2AssetWriter.h index 493ca1c0a8..928b6e71b6 100644 --- a/third_party/libassimp/code/glTF2AssetWriter.h +++ b/third_party/libassimp/code/glTF2/glTF2AssetWriter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/glTF2AssetWriter.inl b/third_party/libassimp/code/glTF2/glTF2AssetWriter.inl similarity index 98% rename from third_party/libassimp/code/glTF2AssetWriter.inl rename to third_party/libassimp/code/glTF2/glTF2AssetWriter.inl index 50d855aaa6..5d1b220645 100644 --- a/third_party/libassimp/code/glTF2AssetWriter.inl +++ b/third_party/libassimp/code/glTF2/glTF2AssetWriter.inl @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -97,10 +97,10 @@ namespace glTF2 { inline void Write(Value& obj, Accessor& a, AssetWriter& w) { obj.AddMember("bufferView", a.bufferView->index, w.mAl); - obj.AddMember("byteOffset", a.byteOffset, w.mAl); + obj.AddMember("byteOffset", (unsigned int)a.byteOffset, w.mAl); obj.AddMember("componentType", int(a.componentType), w.mAl); - obj.AddMember("count", a.count, w.mAl); + obj.AddMember("count", (unsigned int)a.count, w.mAl); obj.AddMember("type", StringRef(AttribType::ToString(a.type)), w.mAl); Value vTmpMax, vTmpMin; @@ -202,6 +202,11 @@ namespace glTF2 { } + inline void Write(Value& /*obj*/, Light& /*c*/, AssetWriter& /*w*/) + { + + } + inline void Write(Value& obj, Image& img, AssetWriter& w) { if (img.bufferView) { @@ -213,7 +218,7 @@ namespace glTF2 { if (img.HasData()) { uri = "data:" + (img.mimeType.empty() ? "application/octet-stream" : img.mimeType); uri += ";base64,"; - Util::EncodeBase64(img.GetData(), img.GetDataLength(), uri); + glTFCommon::Util::EncodeBase64(img.GetData(), img.GetDataLength(), uri); } else { uri = img.uri; @@ -744,6 +749,9 @@ namespace glTF2 { if (!(dict = FindArray(*container, d.mDictId))) { container->AddMember(StringRef(d.mDictId), Value().SetArray().Move(), mDoc.GetAllocator()); dict = FindArray(*container, d.mDictId); + if (nullptr == dict) { + return; + } } for (size_t i = 0; i < d.mObjs.size(); ++i) { diff --git a/third_party/libassimp/code/glTF2Exporter.cpp b/third_party/libassimp/code/glTF2/glTF2Exporter.cpp similarity index 96% rename from third_party/libassimp/code/glTF2Exporter.cpp rename to third_party/libassimp/code/glTF2/glTF2Exporter.cpp index 40db272641..4724c2ef48 100644 --- a/third_party/libassimp/code/glTF2Exporter.cpp +++ b/third_party/libassimp/code/glTF2/glTF2Exporter.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -42,14 +42,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_EXPORT #ifndef ASSIMP_BUILD_NO_GLTF_EXPORTER -#include "glTF2Exporter.h" +#include "glTF2/glTF2Exporter.h" +#include "glTF2/glTF2AssetWriter.h" +#include "PostProcessing/SplitLargeMeshes.h" #include #include #include - -#include "SplitLargeMeshes.h" - #include #include #include @@ -61,8 +60,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include "glTF2AssetWriter.h" - using namespace rapidjson; using namespace Assimp; @@ -156,7 +153,7 @@ static void IdentityMatrix4(mat4& o) { } inline Ref ExportData(Asset& a, std::string& meshName, Ref& buffer, - unsigned int count, void* data, AttribType::Value typeIn, AttribType::Value typeOut, ComponentType compType, bool isIndices = false) + size_t count, void* data, AttribType::Value typeIn, AttribType::Value typeOut, ComponentType compType, bool isIndices = false) { if (!count || !data) { return Ref(); @@ -176,7 +173,7 @@ inline Ref ExportData(Asset& a, std::string& meshName, Ref& bu // bufferView Ref bv = a.bufferViews.Create(a.FindUniqueID(meshName, "view")); bv->buffer = buffer; - bv->byteOffset = unsigned(offset); + bv->byteOffset = offset; bv->byteLength = length; //! The target that the WebGL buffer should be bound to. bv->byteStride = 0; bv->target = isIndices ? BufferViewTarget_ELEMENT_ARRAY_BUFFER : BufferViewTarget_ARRAY_BUFFER; @@ -647,9 +644,7 @@ void ExportSkin(Asset& mAsset, const aiMesh* aimesh, Ref& meshRef, RefGetPointer()[len_p]; unsigned short c = static_cast(f_value); - uint8_t* data = new uint8_t[s_bytesPerComp]; - data = (uint8_t*)&c; - memcpy(&arrys[i*s_bytesPerComp], data, s_bytesPerComp); + memcpy(&arrys[i*s_bytesPerComp], &c, s_bytesPerComp); ++i; } buf->ReplaceData_joint(offset, bytesLen, arrys, bytesLen); @@ -657,9 +652,11 @@ void ExportSkin(Asset& mAsset, const aiMesh* aimesh, Ref& meshRef, RefbufferView->byteLength = s_bytesLen; p.attributes.joint.push_back( vertexJointAccessor ); + delete[] arrys; } - Ref vertexWeightAccessor = ExportData(mAsset, skinRef->id, bufferRef, aimesh->mNumVertices, vertexWeightData, AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT); + Ref vertexWeightAccessor = ExportData(mAsset, skinRef->id, bufferRef, aimesh->mNumVertices, + vertexWeightData, AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT); if ( vertexWeightAccessor ) { p.attributes.weight.push_back( vertexWeightAccessor ); } @@ -732,6 +729,9 @@ void glTF2Exporter::ExportMeshes() /************** Texture coordinates **************/ for (int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) { + if (!aim->HasTextureCoords(i)) + continue; + // Flip UV y coords if (aim -> mNumUVComponents[i] > 1) { for (unsigned int j = 0; j < aim->mNumVertices; ++j) { @@ -748,8 +748,7 @@ void glTF2Exporter::ExportMeshes() } /*************** Vertex colors ****************/ - for (unsigned int indexColorChannel = 0; indexColorChannel < aim->GetNumColorChannels(); ++indexColorChannel) - { + for (unsigned int indexColorChannel = 0; indexColorChannel < aim->GetNumColorChannels(); ++indexColorChannel) { Ref c = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mColors[indexColorChannel], AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT, false); if (c) p.attributes.color.push_back(c); @@ -766,7 +765,7 @@ void glTF2Exporter::ExportMeshes() } } - p.indices = ExportData(*mAsset, meshId, b, unsigned(indices.size()), &indices[0], AttribType::SCALAR, AttribType::SCALAR, ComponentType_UNSIGNED_INT, true); + p.indices = ExportData(*mAsset, meshId, b, indices.size(), &indices[0], AttribType::SCALAR, AttribType::SCALAR, ComponentType_UNSIGNED_INT, true); } switch (aim->mPrimitiveTypes) { @@ -795,8 +794,12 @@ void glTF2Exporter::ExportMeshes() CopyValue(inverseBindMatricesData[idx_joint], invBindMatrixData[idx_joint]); } - Ref invBindMatrixAccessor = ExportData(*mAsset, skinName, b, static_cast(inverseBindMatricesData.size()), invBindMatrixData, AttribType::MAT4, AttribType::MAT4, ComponentType_FLOAT); - if (invBindMatrixAccessor) skinRef->inverseBindMatrices = invBindMatrixAccessor; + Ref invBindMatrixAccessor = ExportData(*mAsset, skinName, b, + static_cast(inverseBindMatricesData.size()), + invBindMatrixData, AttribType::MAT4, AttribType::MAT4, ComponentType_FLOAT); + if (invBindMatrixAccessor) { + skinRef->inverseBindMatrices = invBindMatrixAccessor; + } // Identity Matrix =====> skinRef->bindShapeMatrix // Temporary. Hard-coded identity matrix here @@ -824,10 +827,11 @@ void glTF2Exporter::ExportMeshes() meshNode->skeletons.push_back(rootJoint); meshNode->skin = skinRef; } + delete[] invBindMatrixData; } } -//merges a node's multiple meshes (with one primitive each) into one mesh with multiple primitives +// Merges a node's multiple meshes (with one primitive each) into one mesh with multiple primitives void glTF2Exporter::MergeMeshes() { for (unsigned int n = 0; n < mAsset->nodes.Size(); ++n) { @@ -963,7 +967,7 @@ void glTF2Exporter::ExportMetadata() inline Ref GetSamplerInputRef(Asset& asset, std::string& animId, Ref& buffer, std::vector& times) { - return ExportData(asset, animId, buffer, times.size(), ×[0], AttribType::SCALAR, AttribType::SCALAR, ComponentType_FLOAT); + return ExportData(asset, animId, buffer, (unsigned int)times.size(), ×[0], AttribType::SCALAR, AttribType::SCALAR, ComponentType_FLOAT); } inline void ExtractTranslationSampler(Asset& asset, std::string& animId, Ref& buffer, const aiNodeAnim* nodeChannel, float ticksPerSecond, Animation::Sampler& sampler) diff --git a/third_party/libassimp/code/glTF2Exporter.h b/third_party/libassimp/code/glTF2/glTF2Exporter.h similarity index 99% rename from third_party/libassimp/code/glTF2Exporter.h rename to third_party/libassimp/code/glTF2/glTF2Exporter.h index 06bc5ad400..2dc0837093 100644 --- a/third_party/libassimp/code/glTF2Exporter.h +++ b/third_party/libassimp/code/glTF2/glTF2Exporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/glTF2Importer.cpp b/third_party/libassimp/code/glTF2/glTF2Importer.cpp old mode 100755 new mode 100644 similarity index 82% rename from third_party/libassimp/code/glTF2Importer.cpp rename to third_party/libassimp/code/glTF2/glTF2Importer.cpp index 5d39ec5db1..82c6cbfa8b --- a/third_party/libassimp/code/glTF2Importer.cpp +++ b/third_party/libassimp/code/glTF2/glTF2Importer.cpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -42,10 +42,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ASSIMP_BUILD_NO_GLTF_IMPORTER -#include "glTF2Importer.h" +#include "glTF2/glTF2Importer.h" +#include "glTF2/glTF2Asset.h" +#include "glTF2/glTF2AssetWriter.h" +#include "PostProcessing/MakeVerboseFormat.h" + #include #include - #include #include #include @@ -56,19 +59,15 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include "MakeVerboseFormat.h" - -#include "glTF2Asset.h" -// This is included here so WriteLazyDict's definition is found. -#include "glTF2AssetWriter.h" #include #include using namespace Assimp; using namespace glTF2; +using namespace glTFCommon; namespace { - // generate bitangents from normals and tangents according to spec + // generate bi-tangents from normals and tangents according to spec struct Tangent { aiVector3D xyz; ai_real w; @@ -142,22 +141,23 @@ static aiTextureMapMode ConvertWrappingMode(SamplerWrap gltfWrapMode) } } -//static void CopyValue(const glTF2::vec3& v, aiColor3D& out) -//{ -// out.r = v[0]; out.g = v[1]; out.b = v[2]; -//} +/*static void CopyValue(const glTF2::vec3& v, aiColor3D& out) +{ + out.r = v[0]; out.g = v[1]; out.b = v[2]; +} + static void CopyValue(const glTF2::vec4& v, aiColor4D& out) { out.r = v[0]; out.g = v[1]; out.b = v[2]; out.a = v[3]; -} +}*/ /*static void CopyValue(const glTF2::vec4& v, aiColor3D& out) { out.r = v[0]; out.g = v[1]; out.b = v[2]; }*/ -static void CopyValue(const glTF2::vec3& v, aiColor4D& out) +/*static void CopyValue(const glTF2::vec3& v, aiColor4D& out) { out.r = v[0]; out.g = v[1]; out.b = v[2]; out.a = 1.0; } @@ -170,15 +170,15 @@ static void CopyValue(const glTF2::vec3& v, aiVector3D& out) static void CopyValue(const glTF2::vec4& v, aiQuaternion& out) { out.x = v[0]; out.y = v[1]; out.z = v[2]; out.w = v[3]; -} +}*/ -static void CopyValue(const glTF2::mat4& v, aiMatrix4x4& o) +/*static void CopyValue(const glTF2::mat4& v, aiMatrix4x4& o) { o.a1 = v[ 0]; o.b1 = v[ 1]; o.c1 = v[ 2]; o.d1 = v[ 3]; o.a2 = v[ 4]; o.b2 = v[ 5]; o.c2 = v[ 6]; o.d2 = v[ 7]; o.a3 = v[ 8]; o.b3 = v[ 9]; o.c3 = v[10]; o.d3 = v[11]; o.a4 = v[12]; o.b4 = v[13]; o.c4 = v[14]; o.d4 = v[15]; -} +}*/ inline void SetMaterialColorProperty(Asset& /*r*/, vec4& prop, aiMaterial* mat, const char* pKey, unsigned int type, unsigned int idx) { @@ -190,7 +190,7 @@ inline void SetMaterialColorProperty(Asset& /*r*/, vec4& prop, aiMaterial* mat, inline void SetMaterialColorProperty(Asset& /*r*/, vec3& prop, aiMaterial* mat, const char* pKey, unsigned int type, unsigned int idx) { aiColor4D col; - CopyValue(prop, col); + glTFCommon::CopyValue(prop, col); mat->AddProperty(&col, 1, pKey, type, idx); } @@ -385,7 +385,7 @@ void glTF2Importer::ImportMeshes(glTF2::Asset& r) aim->mName = mesh.name.empty() ? mesh.id : mesh.name; if (mesh.primitives.size() > 1) { - size_t& len = aim->mName.length; + ai_uint32& len = aim->mName.length; aim->mName.data[len] = '-'; len += 1 + ASSIMP_itoa10(aim->mName.data + len + 1, unsigned(MAXLEN - len - 1), p); } @@ -412,7 +412,7 @@ void glTF2Importer::ImportMeshes(glTF2::Asset& r) Mesh::Primitive::Attributes& attr = prim.attributes; if (attr.position.size() > 0 && attr.position[0]) { - aim->mNumVertices = attr.position[0]->count; + aim->mNumVertices = static_cast(attr.position[0]->count); attr.position[0]->ExtractData(aim->mVertices); } @@ -438,6 +438,14 @@ void glTF2Importer::ImportMeshes(glTF2::Asset& r) } } + for (size_t c = 0; c < attr.color.size() && c < AI_MAX_NUMBER_OF_COLOR_SETS; ++c) { + if (attr.color[c]->count != aim->mNumVertices) { + DefaultLogger::get()->warn("Color stream size in mesh \"" + mesh.name + + "\" does not match the vertex count"); + continue; + } + attr.color[c]->ExtractData(aim->mColors[c]); + } for (size_t tc = 0; tc < attr.texcoord.size() && tc < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++tc) { if (attr.texcoord[tc]->count != aim->mNumVertices) { DefaultLogger::get()->warn("Texcoord stream size in mesh \"" + mesh.name + @@ -502,10 +510,10 @@ void glTF2Importer::ImportMeshes(glTF2::Asset& r) aiFace* faces = 0; - unsigned int nFaces = 0; + size_t nFaces = 0; if (prim.indices) { - unsigned int count = prim.indices->count; + size_t count = prim.indices->count; Accessor::Indexer data = prim.indices->GetIndexer(); ai_assert(data.IsValid()); @@ -656,8 +664,8 @@ void glTF2Importer::ImportMeshes(glTF2::Asset& r) if (faces) { aim->mFaces = faces; - aim->mNumFaces = nFaces; - ai_assert(CheckValidFacesIndices(faces, nFaces, aim->mNumVertices)); + aim->mNumFaces = static_cast(nFaces); + ai_assert(CheckValidFacesIndices(faces, static_cast(nFaces), aim->mNumVertices)); } if (prim.material) { @@ -693,12 +701,80 @@ void glTF2Importer::ImportCameras(glTF2::Asset& r) if (cam.type == Camera::Perspective) { aicam->mAspect = cam.cameraProperties.perspective.aspectRatio; - aicam->mHorizontalFOV = cam.cameraProperties.perspective.yfov * aicam->mAspect; + aicam->mHorizontalFOV = cam.cameraProperties.perspective.yfov * ((aicam->mAspect == 0.f) ? 1.f : aicam->mAspect); aicam->mClipPlaneFar = cam.cameraProperties.perspective.zfar; aicam->mClipPlaneNear = cam.cameraProperties.perspective.znear; + } else { + aicam->mClipPlaneFar = cam.cameraProperties.ortographic.zfar; + aicam->mClipPlaneNear = cam.cameraProperties.ortographic.znear; + aicam->mHorizontalFOV = 0.0; + aicam->mAspect = 1.0f; + if (0.f != cam.cameraProperties.ortographic.ymag ) { + aicam->mAspect = cam.cameraProperties.ortographic.xmag / cam.cameraProperties.ortographic.ymag; + } } - else { - // assimp does not support orthographic cameras + } +} + +void glTF2Importer::ImportLights(glTF2::Asset& r) +{ + if (!r.lights.Size()) + return; + + mScene->mNumLights = r.lights.Size(); + mScene->mLights = new aiLight*[r.lights.Size()]; + + for (size_t i = 0; i < r.lights.Size(); ++i) { + Light& light = r.lights[i]; + + aiLight* ail = mScene->mLights[i] = new aiLight(); + + switch (light.type) + { + case Light::Directional: + ail->mType = aiLightSource_DIRECTIONAL; break; + case Light::Point: + ail->mType = aiLightSource_POINT; break; + case Light::Spot: + ail->mType = aiLightSource_SPOT; break; + } + + if (ail->mType != aiLightSource_POINT) + { + ail->mDirection = aiVector3D(0.0f, 0.0f, -1.0f); + ail->mUp = aiVector3D(0.0f, 1.0f, 0.0f); + } + + vec3 colorWithIntensity = { light.color[0] * light.intensity, light.color[1] * light.intensity, light.color[2] * light.intensity }; + CopyValue(colorWithIntensity, ail->mColorAmbient); + CopyValue(colorWithIntensity, ail->mColorDiffuse); + CopyValue(colorWithIntensity, ail->mColorSpecular); + + if (ail->mType == aiLightSource_DIRECTIONAL) + { + ail->mAttenuationConstant = 1.0; + ail->mAttenuationLinear = 0.0; + ail->mAttenuationQuadratic = 0.0; + } + else + { + //in PBR attenuation is calculated using inverse square law which can be expressed + //using assimps equation: 1/(att0 + att1 * d + att2 * d*d) with the following parameters + //this is correct equation for the case when range (see + //https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual) + //is not present. When range is not present it is assumed that it is infinite and so numerator is 1. + //When range is present then numerator might be any value in range [0,1] and then assimps equation + //will not suffice. In this case range is added into metadata in ImportNode function + //and its up to implementation to read it when it wants to + ail->mAttenuationConstant = 0.0; + ail->mAttenuationLinear = 0.0; + ail->mAttenuationQuadratic = 1.0; + } + + if (ail->mType == aiLightSource_SPOT) + { + ail->mAngleInnerCone = light.innerConeAngle; + ail->mAngleOuterCone = light.outerConeAngle; } } } @@ -742,7 +818,7 @@ static void BuildVertexWeightMapping(Mesh::Primitive& primitive, std::vectorcount; + size_t num_vertices = attr.weight[0]->count; struct Weights { float values[4]; }; Weights* weights = nullptr; @@ -757,14 +833,20 @@ static void BuildVertexWeightMapping(Mesh::Primitive& primitive, std::vectorExtractData(indices16); } + // + if (nullptr == indices8 && nullptr == indices16) { + // Something went completely wrong! + ai_assert(false); + return; + } - for (int i = 0; i < num_vertices; ++i) { + for (size_t i = 0; i < num_vertices; ++i) { for (int j = 0; j < 4; ++j) { const unsigned int bone = (indices8!=nullptr) ? indices8[i].values[j] : indices16[i].values[j]; const float weight = weights[i].values[j]; if (weight > 0 && bone < map.size()) { map[bone].reserve(8); - map[bone].emplace_back(i, weight); + map[bone].emplace_back(static_cast(i), weight); } } } @@ -774,13 +856,16 @@ static void BuildVertexWeightMapping(Mesh::Primitive& primitive, std::vector& meshOffsets, glTF2::Ref& ptr) { Node& node = *ptr; - std::string nameOrId = node.name.empty() ? node.id : node.name; - - aiNode* ainode = new aiNode(nameOrId); + aiNode* ainode = new aiNode(GetNodeName(node)); if (!node.children.empty()) { ainode->mNumChildren = unsigned(node.children.size()); @@ -807,7 +892,7 @@ aiNode* ImportNode(aiScene* pScene, glTF2::Asset& r, std::vector& if (node.skin) { for (int primitiveNo = 0; primitiveNo < count; ++primitiveNo) { aiMesh* mesh = pScene->mMeshes[meshOffsets[mesh_idx]+primitiveNo]; - mesh->mNumBones = node.skin->jointNames.size(); + mesh->mNumBones = static_cast(node.skin->jointNames.size()); mesh->mBones = new aiBone*[mesh->mNumBones]; // GLTF and Assimp choose to store bone weights differently. @@ -822,22 +907,45 @@ aiNode* ImportNode(aiScene* pScene, glTF2::Asset& r, std::vector& std::vector> weighting(mesh->mNumBones); BuildVertexWeightMapping(node.meshes[0]->primitives[primitiveNo], weighting); - for (size_t i = 0; i < mesh->mNumBones; ++i) { + mat4* pbindMatrices = nullptr; + node.skin->inverseBindMatrices->ExtractData(pbindMatrices); + + for (uint32_t i = 0; i < mesh->mNumBones; ++i) { aiBone* bone = new aiBone(); Ref joint = node.skin->jointNames[i]; - bone->mName = joint->name; + if (!joint->name.empty()) { + bone->mName = joint->name; + } else { + // Assimp expects each bone to have a unique name. + static const std::string kDefaultName = "bone_"; + char postfix[10] = {0}; + ASSIMP_itoa10(postfix, i); + bone->mName = (kDefaultName + postfix); + } GetNodeTransform(bone->mOffsetMatrix, *joint); + CopyValue(pbindMatrices[i], bone->mOffsetMatrix); + std::vector& weights = weighting[i]; - bone->mNumWeights = weights.size(); + bone->mNumWeights = static_cast(weights.size()); if (bone->mNumWeights > 0) { - bone->mWeights = new aiVertexWeight[bone->mNumWeights]; - memcpy(bone->mWeights, weights.data(), bone->mNumWeights * sizeof(aiVertexWeight)); + bone->mWeights = new aiVertexWeight[bone->mNumWeights]; + memcpy(bone->mWeights, weights.data(), bone->mNumWeights * sizeof(aiVertexWeight)); + } else { + // Assimp expects all bones to have at least 1 weight. + bone->mWeights = new aiVertexWeight[1]; + bone->mNumWeights = 1; + bone->mWeights->mVertexId = 0; + bone->mWeights->mWeight = 0.f; } mesh->mBones[i] = bone; } + + if (pbindMatrices) { + delete[] pbindMatrices; + } } } @@ -851,6 +959,18 @@ aiNode* ImportNode(aiScene* pScene, glTF2::Asset& r, std::vector& pScene->mCameras[node.camera.GetIndex()]->mName = ainode->mName; } + if (node.light) { + pScene->mLights[node.light.GetIndex()]->mName = ainode->mName; + + //range is optional - see https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual + //it is added to meta data of parent node, because there is no other place to put it + if (node.light->range.isPresent) + { + ainode->mMetaData = aiMetadata::Alloc(1); + ainode->mMetaData->Set(0, "PBR_LightRange", node.light->range.value); + } + } + return ainode; } @@ -882,7 +1002,12 @@ void glTF2Importer::ImportNodes(glTF2::Asset& r) } struct AnimationSamplers { - AnimationSamplers() : translation(nullptr), rotation(nullptr), scale(nullptr) {} + AnimationSamplers() + : translation(nullptr) + , rotation(nullptr) + , scale(nullptr) { + // empty + } Animation::Sampler* translation; Animation::Sampler* rotation; @@ -892,7 +1017,7 @@ struct AnimationSamplers { aiNodeAnim* CreateNodeAnim(glTF2::Asset& r, Node& node, AnimationSamplers& samplers) { aiNodeAnim* anim = new aiNodeAnim(); - anim->mNodeName = node.name; + anim->mNodeName = GetNodeName(node); static const float kMillisecondsFromSeconds = 1000.f; @@ -901,7 +1026,7 @@ aiNodeAnim* CreateNodeAnim(glTF2::Asset& r, Node& node, AnimationSamplers& sampl samplers.translation->input->ExtractData(times); aiVector3D* values = nullptr; samplers.translation->output->ExtractData(values); - anim->mNumPositionKeys = samplers.translation->input->count; + anim->mNumPositionKeys = static_cast(samplers.translation->input->count); anim->mPositionKeys = new aiVectorKey[anim->mNumPositionKeys]; for (unsigned int i = 0; i < anim->mNumPositionKeys; ++i) { anim->mPositionKeys[i].mTime = times[i] * kMillisecondsFromSeconds; @@ -923,7 +1048,7 @@ aiNodeAnim* CreateNodeAnim(glTF2::Asset& r, Node& node, AnimationSamplers& sampl samplers.rotation->input->ExtractData(times); aiQuaternion* values = nullptr; samplers.rotation->output->ExtractData(values); - anim->mNumRotationKeys = samplers.rotation->input->count; + anim->mNumRotationKeys = static_cast(samplers.rotation->input->count); anim->mRotationKeys = new aiQuatKey[anim->mNumRotationKeys]; for (unsigned int i = 0; i < anim->mNumRotationKeys; ++i) { anim->mRotationKeys[i].mTime = times[i] * kMillisecondsFromSeconds; @@ -936,7 +1061,7 @@ aiNodeAnim* CreateNodeAnim(glTF2::Asset& r, Node& node, AnimationSamplers& sampl delete[] values; } else if (node.rotation.isPresent) { anim->mNumRotationKeys = 1; - anim->mRotationKeys = new aiQuatKey(); + anim->mRotationKeys = new aiQuatKey[anim->mNumRotationKeys]; anim->mRotationKeys->mTime = 0.f; anim->mRotationKeys->mValue.x = node.rotation.value[0]; anim->mRotationKeys->mValue.y = node.rotation.value[1]; @@ -949,7 +1074,7 @@ aiNodeAnim* CreateNodeAnim(glTF2::Asset& r, Node& node, AnimationSamplers& sampl samplers.scale->input->ExtractData(times); aiVector3D* values = nullptr; samplers.scale->output->ExtractData(values); - anim->mNumScalingKeys = samplers.scale->input->count; + anim->mNumScalingKeys = static_cast(samplers.scale->input->count); anim->mScalingKeys = new aiVectorKey[anim->mNumScalingKeys]; for (unsigned int i = 0; i < anim->mNumScalingKeys; ++i) { anim->mScalingKeys[i].mTime = times[i] * kMillisecondsFromSeconds; @@ -959,7 +1084,7 @@ aiNodeAnim* CreateNodeAnim(glTF2::Asset& r, Node& node, AnimationSamplers& sampl delete[] values; } else if (node.scale.isPresent) { anim->mNumScalingKeys = 1; - anim->mScalingKeys = new aiVectorKey(); + anim->mScalingKeys = new aiVectorKey[anim->mNumScalingKeys]; anim->mScalingKeys->mTime = 0.f; anim->mScalingKeys->mValue.x = node.scale.value[0]; anim->mScalingKeys->mValue.y = node.scale.value[1]; @@ -1013,18 +1138,19 @@ void glTF2Importer::ImportAnimations(glTF2::Asset& r) std::unordered_map samplers = GatherSamplers(anim); - ai_anim->mNumChannels = r.skins.Size() > 0 ? r.skins[0].jointNames.size() : 0; + ai_anim->mNumChannels = static_cast(samplers.size()); if (ai_anim->mNumChannels > 0) { ai_anim->mChannels = new aiNodeAnim*[ai_anim->mNumChannels]; int j = 0; - for (auto& iter : r.skins[0].jointNames) { - ai_anim->mChannels[j] = CreateNodeAnim(r, *iter, samplers[iter.GetIndex()]); + for (auto& iter : samplers) { + ai_anim->mChannels[j] = CreateNodeAnim(r, r.nodes[iter.first], iter.second); ++j; } } // Use the latest keyframe for the duration of the animation double maxDuration = 0; + unsigned int maxNumberOfKeys = 0; for (unsigned int j = 0; j < ai_anim->mNumChannels; ++j) { auto chan = ai_anim->mChannels[j]; if (chan->mNumPositionKeys) { @@ -1032,21 +1158,25 @@ void glTF2Importer::ImportAnimations(glTF2::Asset& r) if (lastPosKey.mTime > maxDuration) { maxDuration = lastPosKey.mTime; } + maxNumberOfKeys = std::max(maxNumberOfKeys, chan->mNumPositionKeys); } if (chan->mNumRotationKeys) { auto lastRotKey = chan->mRotationKeys[chan->mNumRotationKeys - 1]; if (lastRotKey.mTime > maxDuration) { maxDuration = lastRotKey.mTime; } + maxNumberOfKeys = std::max(maxNumberOfKeys, chan->mNumRotationKeys); } if (chan->mNumScalingKeys) { auto lastScaleKey = chan->mScalingKeys[chan->mNumScalingKeys - 1]; if (lastScaleKey.mTime > maxDuration) { maxDuration = lastScaleKey.mTime; } + maxNumberOfKeys = std::max(maxNumberOfKeys, chan->mNumScalingKeys); } } ai_anim->mDuration = maxDuration; + ai_anim->mTicksPerSecond = (maxNumberOfKeys > 0 && maxDuration > 0) ? (maxNumberOfKeys / (maxDuration/1000)) : 30; mScene->mAnimations[i] = ai_anim; } @@ -1098,7 +1228,11 @@ void glTF2Importer::ImportEmbeddedTextures(glTF2::Asset& r) } } -void glTF2Importer::InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) { +void glTF2Importer::InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) +{ + // clean all member arrays + meshOffsets.clear(); + embeddedTexIdxs.clear(); this->mScene = pScene; @@ -1116,6 +1250,7 @@ void glTF2Importer::InternReadFile(const std::string& pFile, aiScene* pScene, IO ImportMeshes(asset); ImportCameras(asset); + ImportLights(asset); ImportNodes(asset); diff --git a/third_party/libassimp/code/glTF2Importer.h b/third_party/libassimp/code/glTF2/glTF2Importer.h similarity index 98% rename from third_party/libassimp/code/glTF2Importer.h rename to third_party/libassimp/code/glTF2/glTF2Importer.h index 7414e2f95c..091b61ee62 100644 --- a/third_party/libassimp/code/glTF2Importer.h +++ b/third_party/libassimp/code/glTF2/glTF2Importer.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/code/makefile.mingw b/third_party/libassimp/code/makefile.mingw deleted file mode 100644 index 711d57f57e..0000000000 --- a/third_party/libassimp/code/makefile.mingw +++ /dev/null @@ -1,105 +0,0 @@ -### USE OF THIS MAKEFILE IS NOT RECOMMENDED. -### It is no longer maintained. Use CMAKE instead. - -# --------------------------------------------------------------------------- -# Makefile for Open Asset Import Library (MinGW32-make) -# aramis_acg@users.sourceforge.net -# - just a quick'n'dirty one, could be buggy ... -# -# Usage: mingw32-make -f makefile.mingw - -# TARGETS: -# all Build a shared so from the whole library -# clean Cleanup object files, prepare for rebuild -# static Build a static library (*.a) - -# MACROS: (make clean before you change one) -# NOBOOST=1 Build against boost workaround -# SINGLETHREADED=1 Build single-threaded library -# DEBUG=1 Build debug build of library -# -# --------------------------------------------------------------------------- - -# C++ object files -OBJECTS := $(patsubst %.cpp,%.o, $(wildcard *.cpp)) -OBJECTS += $(patsubst %.cpp,%.o, $(wildcard extra/*.cpp)) -OBJECTS += $(patsubst %.cpp,%.o, $(wildcard ./../contrib/irrXML/*.cpp)) - -# C object files -OBJECTSC := $(patsubst %.c,%.oc, $(wildcard ./../contrib/zlib/*.c)) -OBJECTSC += $(patsubst %.c,%.oc, $(wildcard ./../contrib/ConvertUTF/*.c)) -OBJECTSC += $(patsubst %.c,%.oc, $(wildcard ./../contrib/unzip/*.c)) - -# Include flags for gcc -INCLUDEFLAGS = - -# Preprocessor defines for gcc -DEFINEFLAGS = - -# Suffix for the output binary, represents build type -NAMESUFFIX = - -# Output path for binaries -BINPATH = ../bin/mingw/ - -# GCC compiler flags -CPPFLAGS=-Wall - -# Setup environment for noboost build -ifeq ($(NOBOOST),1) - SINGLETHREADED = 1 - INCLUDEFLAGS += -I./BoostWorkaround/ - DEFINEFLAGS += -DASSIMP_BUILD_BOOST_WORKAROUND -# NAMESUFFIX += -noboost -else - # adjust this manually if your boost is stored elsewhere - INCLUDEFLAGS += -I"C:/Program Files/boost/boost_1_38" - #INCLUDEFLAGS += -I"$(BOOST_DIR)" - -endif - -# Setup environment for st build -ifeq ($(SINGLETHREADED),1) - DEFINEFLAGS += -DASSIMP_BUILD_SINGLETHREADED -# NAMESUFFIX += -st -endif - -# Setup environment for debug build -ifeq ($(DEBUG),1) - DEFINEFLAGS += -D_DEBUG -DDEBUG - CPPFLAGS += -g -# NAMESUFFIX += -debug -else - CPPFLAGS += -O2 -s - DEFINEFLAGS += -DNDEBUG -D_NDEBUG -endif - -# Output name of shared library -SHARED_TARGET = $(BINPATH)/libassimp$(NAMESUFFIX).so - -# Output name of static library -STATIC = $(BINPATH)/libassimp$(NAMESUFFIX).a - -# target: all -# usage : build a shared library (*.so) -all: $(SHARED_TARGET) - -$(SHARED_TARGET): $(OBJECTS) $(OBJECTSC) - gcc -o $@ $(OBJECTS) $(OBJECTSC) -shared -lstdc++ -%.o:%.cpp - $(CXX) -c $(CPPFLAGS) $? -o $@ $(INCLUDEFLAGS) $(DEFINEFLAGS) -%.oc:%.c - $(CXX) -x c -c -ansi $(CPPFLAGS) $? -o $@ - -# target: clean -# usage : cleanup all object files, prepare for a rebuild -.PHONY: clean -clean: - -del *.o .\..\contrib\irrXML\*.o .\..\contrib\zlib\*.oc .\..\contrib\unzip\*.oc .\..\contrib\ConvertUTF\*.oc - -# target: static -# usage : build a static library (*.a) -static: $(STATIC) -$(STATIC): $(OBJECTS) $(OBJECTSC) - ar rcs $@ $(OBJECTS) $(OBJECTSC) - diff --git a/third_party/libassimp/code/res/assimp.rc b/third_party/libassimp/code/res/assimp.rc index 0fe98c05d7..daecf9cf59 100644 --- a/third_party/libassimp/code/res/assimp.rc +++ b/third_party/libassimp/code/res/assimp.rc @@ -1,7 +1,7 @@ // Microsoft Visual C++ generated resource script. // #include "resource.h" -#include "..\..\revision.h" +#include "revision.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// @@ -31,8 +31,8 @@ LANGUAGE LANG_GERMAN, SUBLANG_GERMAN // VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,1,SVNRevision, 0 - PRODUCTVERSION 1,1,SVNRevision,0 + FILEVERSION VER_FILEVERSION + PRODUCTVERSION VER_FILEVERSION FILEFLAGSMASK 0x17L #ifdef _DEBUG FILEFLAGS 0x1L @@ -50,12 +50,12 @@ BEGIN VALUE "Comments", "Licensed under a 3-clause BSD license" VALUE "CompanyName", "assimp team" VALUE "FileDescription", "Open Asset Import Library" - VALUE "FileVersion", 1,1,SVNRevision,0 + VALUE "FileVersion", VER_FILEVERSION VALUE "InternalName", "assimp " - VALUE "LegalCopyright", "Copyright (C) 2006-2010" - VALUE "OriginalFilename", "assimpNN.dll" + VALUE "LegalCopyright", "Copyright (C) 2006-2019" + VALUE "OriginalFilename", VER_ORIGINAL_FILENAME_STR VALUE "ProductName", "Open Asset Import Library" - VALUE "ProductVersion", 1,1,SVNRevision,0 + VALUE "ProductVersion", VER_FILEVERSION_STR ,0 END END diff --git a/third_party/libassimp/code/res/resource.h b/third_party/libassimp/code/res/resource.h index 37d39284fe..c28c05073e 100644 --- a/third_party/libassimp/code/res/resource.h +++ b/third_party/libassimp/code/res/resource.h @@ -2,8 +2,8 @@ // Microsoft Visual C++ generated include file. // Used by assimp.rc -// Nchste Standardwerte fr neue Objekte -// +// Next standard values for new objects +// #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 diff --git a/third_party/libassimp/contrib/clipper/clipper.cpp b/third_party/libassimp/contrib/clipper/clipper.cpp index 074f22b214..857cd1c3ed 100644 --- a/third_party/libassimp/contrib/clipper/clipper.cpp +++ b/third_party/libassimp/contrib/clipper/clipper.cpp @@ -371,6 +371,9 @@ inline bool PointsEqual( const IntPoint &pt1, const IntPoint &pt2) bool Orientation(OutRec *outRec, bool UseFullInt64Range) { + if (!outRec->pts) + return 0.0; + //first make sure bottomPt is correctly assigned ... OutPt *opBottom = outRec->pts, *op = outRec->pts->next; while (op != outRec->pts) @@ -434,6 +437,9 @@ double Area(const Polygon &poly) double Area(const OutRec &outRec, bool UseFullInt64Range) { + if (!outRec.pts) + return 0.0; + OutPt *op = outRec.pts; if (UseFullInt64Range) { Int128 a(0); @@ -3085,9 +3091,9 @@ void Clipper::JoinCommonEdges(bool fixHoleLinkages) FixupOutPolygon(*outRec1); FixupOutPolygon(*outRec2); - if (Orientation(outRec1, m_UseFullRange) != (Area(*outRec1, m_UseFullRange) > 0)) + if (outRec1->pts && (Orientation(outRec1, m_UseFullRange) != (Area(*outRec1, m_UseFullRange) > 0))) DisposeBottomPt(*outRec1); - if (Orientation(outRec2, m_UseFullRange) != (Area(*outRec2, m_UseFullRange) > 0)) + if (outRec2->pts && (Orientation(outRec2, m_UseFullRange) != (Area(*outRec2, m_UseFullRange) > 0))) DisposeBottomPt(*outRec2); } else diff --git a/third_party/libassimp/contrib/gtest/.gitignore b/third_party/libassimp/contrib/gtest/.gitignore deleted file mode 100644 index 4b7be4b91b..0000000000 --- a/third_party/libassimp/contrib/gtest/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# python -*.pyc diff --git a/third_party/libassimp/contrib/gtest/test/gtest-param-test_test.cc b/third_party/libassimp/contrib/gtest/test/gtest-param-test_test.cc index 8b278bb94b..857f6c5e53 100644 --- a/third_party/libassimp/contrib/gtest/test/gtest-param-test_test.cc +++ b/third_party/libassimp/contrib/gtest/test/gtest-param-test_test.cc @@ -141,7 +141,7 @@ void VerifyGenerator(const ParamGenerator& generator, << ", expected_values[i] is " << PrintValue(expected_values[i]) << ", *it is " << PrintValue(*it) << ", and 'it' is an iterator created with the copy constructor.\n"; - it++; + ++it; } EXPECT_TRUE(it == generator.end()) << "At the presumed end of sequence when accessing via an iterator " @@ -161,7 +161,7 @@ void VerifyGenerator(const ParamGenerator& generator, << ", expected_values[i] is " << PrintValue(expected_values[i]) << ", *it is " << PrintValue(*it) << ", and 'it' is an iterator created with the copy constructor.\n"; - it++; + ++it; } EXPECT_TRUE(it == generator.end()) << "At the presumed end of sequence when accessing via an iterator " @@ -196,7 +196,7 @@ TEST(IteratorTest, ParamIteratorConformsToForwardIteratorConcept) { << "element same as its source points to"; // Verifies that iterator assignment works as expected. - it++; + ++it; EXPECT_FALSE(*it == *it2); it2 = it; EXPECT_TRUE(*it == *it2) << "Assigned iterators must point to the " @@ -215,7 +215,7 @@ TEST(IteratorTest, ParamIteratorConformsToForwardIteratorConcept) { // Verifies that prefix and postfix operator++() advance an iterator // all the same. it2 = it; - it++; + ++it; ++it2; EXPECT_TRUE(*it == *it2); } diff --git a/third_party/libassimp/contrib/irrXML/CMakeLists.txt b/third_party/libassimp/contrib/irrXML/CMakeLists.txt index 48941970a1..7f58af3d85 100644 --- a/third_party/libassimp/contrib/irrXML/CMakeLists.txt +++ b/third_party/libassimp/contrib/irrXML/CMakeLists.txt @@ -13,10 +13,17 @@ if ( MSVC ) ADD_DEFINITIONS( -D_CRT_SECURE_NO_WARNINGS ) endif ( MSVC ) -add_library(IrrXML STATIC ${IrrXML_SRCS}) +IF(CMAKE_SYSTEM_NAME MATCHES "(Darwin|FreeBSD)") + add_library(IrrXML ${IrrXML_SRCS}) +ELSE() + add_library(IrrXML STATIC ${IrrXML_SRCS}) +ENDIF() set(IRRXML_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}" CACHE INTERNAL "IrrXML_Include" ) set(IRRXML_LIBRARY "IrrXML" CACHE INTERNAL "IrrXML" ) install(TARGETS IrrXML + LIBRARY DESTINATION ${ASSIMP_LIB_INSTALL_DIR} ARCHIVE DESTINATION ${ASSIMP_LIB_INSTALL_DIR} + RUNTIME DESTINATION ${ASSIMP_BIN_INSTALL_DIR} + FRAMEWORK DESTINATION ${ASSIMP_LIB_INSTALL_DIR} COMPONENT ${LIBASSIMP_COMPONENT}) diff --git a/third_party/libassimp/contrib/irrXML/CXMLReaderImpl.h b/third_party/libassimp/contrib/irrXML/CXMLReaderImpl.h index 7d33b94045..6f3bec5fa1 100644 --- a/third_party/libassimp/contrib/irrXML/CXMLReaderImpl.h +++ b/third_party/libassimp/contrib/irrXML/CXMLReaderImpl.h @@ -10,8 +10,11 @@ #include "irrArray.h" #include +#include +#include +#include +//using namespace Assimp; -using namespace Assimp; #ifdef _DEBUG #define IRR_DEBUGPRINT(x) printf((x)); @@ -162,7 +165,8 @@ public: return 0; core::stringc c = attr->Value.c_str(); - return fast_atof(c.c_str()); + return static_cast(atof(c.c_str())); + //return fast_atof(c.c_str()); } @@ -174,7 +178,8 @@ public: return 0; core::stringc c = attrvalue; - return fast_atof(c.c_str()); + return static_cast(atof(c.c_str())); + //return fast_atof(c.c_str()); } @@ -428,7 +433,7 @@ private: ++P; // remove trailing whitespace, if any - while( isspace( P[-1])) + while( std::isspace( P[-1])) --P; NodeName = core::string(pBeginClose, (int)(P - pBeginClose)); diff --git a/third_party/libassimp/contrib/irrXML/irrString.h b/third_party/libassimp/contrib/irrXML/irrString.h index af21b8e518..ff0097b71b 100644 --- a/third_party/libassimp/contrib/irrXML/irrString.h +++ b/third_party/libassimp/contrib/irrXML/irrString.h @@ -19,7 +19,7 @@ so you can assign unicode to string and ascii to string Note that the conversation between both is not done using an encoding. Known bugs: -Special characters like '', '' and '' are ignored in the +Special characters like 'Ä', 'Ü' and 'Ö' are ignored in the methods make_upper, make_lower and equals_ignore_case. */ template diff --git a/third_party/libassimp/contrib/irrXML/irrXML.cpp b/third_party/libassimp/contrib/irrXML/irrXML.cpp index 532eed5446..5a4b04507b 100644 --- a/third_party/libassimp/contrib/irrXML/irrXML.cpp +++ b/third_party/libassimp/contrib/irrXML/irrXML.cpp @@ -9,7 +9,7 @@ #include "irrXML.h" #include "irrString.h" #include "irrArray.h" -#include +//#include #include "CXMLReaderImpl.h" namespace irr @@ -18,7 +18,7 @@ namespace io { //! Implementation of the file read callback for ordinary files -class CFileReadCallBack : public IFileReadCallBack +class IRRXML_API CFileReadCallBack : public IFileReadCallBack { public: diff --git a/third_party/libassimp/contrib/irrXML/irrXML.h b/third_party/libassimp/contrib/irrXML/irrXML.h index b51ddeb543..d724b31622 100644 --- a/third_party/libassimp/contrib/irrXML/irrXML.h +++ b/third_party/libassimp/contrib/irrXML/irrXML.h @@ -7,6 +7,12 @@ #include +#ifdef _WIN32 +# define IRRXML_API __declspec(dllexport) +#else +# define IRRXML_API __attribute__ ((visibility("default"))) +#endif // _WIN32 + /** \mainpage irrXML 1.2 API documentation

@@ -209,7 +215,7 @@ namespace io two methods to read your data and give a pointer to an instance of your implementation when calling createIrrXMLReader(), createIrrXMLReaderUTF16() or createIrrXMLReaderUTF32() */ - class IFileReadCallBack + class IRRXML_API IFileReadCallBack { public: @@ -409,7 +415,7 @@ namespace io \return Returns a pointer to the created xml parser. This pointer should be deleted using 'delete' after no longer needed. Returns 0 if an error occured and the file could not be opened. */ - IrrXMLReader* createIrrXMLReader(const char* filename); + IRRXML_API IrrXMLReader* createIrrXMLReader(const char* filename); //! Creates an instance of an UFT-8 or ASCII character xml parser. /** This means that all character data will be returned in 8 bit ASCII or UTF-8. The file to read can @@ -421,7 +427,7 @@ namespace io \return Returns a pointer to the created xml parser. This pointer should be deleted using 'delete' after no longer needed. Returns 0 if an error occured and the file could not be opened. */ - IrrXMLReader* createIrrXMLReader(FILE* file); + IRRXML_API IrrXMLReader* createIrrXMLReader(FILE* file); //! Creates an instance of an UFT-8 or ASCII character xml parser. /** This means that all character data will be returned in 8 bit ASCII or UTF-8. The file to read can @@ -434,7 +440,7 @@ namespace io \return Returns a pointer to the created xml parser. This pointer should be deleted using 'delete' after no longer needed. Returns 0 if an error occured and the file could not be opened. */ - IrrXMLReader* createIrrXMLReader(IFileReadCallBack* callback); + IRRXML_API IrrXMLReader* createIrrXMLReader(IFileReadCallBack* callback); //! Creates an instance of an UFT-16 xml parser. /** This means that @@ -446,7 +452,7 @@ namespace io \return Returns a pointer to the created xml parser. This pointer should be deleted using 'delete' after no longer needed. Returns 0 if an error occured and the file could not be opened. */ - IrrXMLReaderUTF16* createIrrXMLReaderUTF16(const char* filename); + IRRXML_API IrrXMLReaderUTF16* createIrrXMLReaderUTF16(const char* filename); //! Creates an instance of an UFT-16 xml parser. /** This means that all character data will be returned in UTF-16. The file to read can @@ -458,7 +464,7 @@ namespace io \return Returns a pointer to the created xml parser. This pointer should be deleted using 'delete' after no longer needed. Returns 0 if an error occured and the file could not be opened. */ - IrrXMLReaderUTF16* createIrrXMLReaderUTF16(FILE* file); + IRRXML_API IrrXMLReaderUTF16* createIrrXMLReaderUTF16(FILE* file); //! Creates an instance of an UFT-16 xml parser. /** This means that all character data will be returned in UTF-16. The file to read can @@ -471,7 +477,7 @@ namespace io \return Returns a pointer to the created xml parser. This pointer should be deleted using 'delete' after no longer needed. Returns 0 if an error occured and the file could not be opened. */ - IrrXMLReaderUTF16* createIrrXMLReaderUTF16(IFileReadCallBack* callback); + IRRXML_API IrrXMLReaderUTF16* createIrrXMLReaderUTF16(IFileReadCallBack* callback); //! Creates an instance of an UFT-32 xml parser. @@ -483,7 +489,7 @@ namespace io \return Returns a pointer to the created xml parser. This pointer should be deleted using 'delete' after no longer needed. Returns 0 if an error occured and the file could not be opened. */ - IrrXMLReaderUTF32* createIrrXMLReaderUTF32(const char* filename); + IRRXML_API IrrXMLReaderUTF32* createIrrXMLReaderUTF32(const char* filename); //! Creates an instance of an UFT-32 xml parser. /** This means that all character data will be returned in UTF-32. The file to read can @@ -495,7 +501,7 @@ namespace io \return Returns a pointer to the created xml parser. This pointer should be deleted using 'delete' after no longer needed. Returns 0 if an error occured and the file could not be opened. */ - IrrXMLReaderUTF32* createIrrXMLReaderUTF32(FILE* file); + IRRXML_API IrrXMLReaderUTF32* createIrrXMLReaderUTF32(FILE* file); //! Creates an instance of an UFT-32 xml parser. /** This means that @@ -509,7 +515,7 @@ namespace io \return Returns a pointer to the created xml parser. This pointer should be deleted using 'delete' after no longer needed. Returns 0 if an error occured and the file could not be opened. */ - IrrXMLReaderUTF32* createIrrXMLReaderUTF32(IFileReadCallBack* callback); + IRRXML_API IrrXMLReaderUTF32* createIrrXMLReaderUTF32(IFileReadCallBack* callback); /*! \file irrxml.h diff --git a/third_party/libassimp/contrib/poly2tri/AUTHORS b/third_party/libassimp/contrib/poly2tri/AUTHORS index 1736f14bb2..aa390660df 100644 --- a/third_party/libassimp/contrib/poly2tri/AUTHORS +++ b/third_party/libassimp/contrib/poly2tri/AUTHORS @@ -1,7 +1,7 @@ Primary Contributors: Mason Green (C++, Python) - Thomas hln (Java) + Thomas Åhlén (Java) Other Contributors: diff --git a/third_party/libassimp/contrib/stb_image/stb_image.h b/third_party/libassimp/contrib/stb_image/stb_image.h new file mode 100644 index 0000000000..571b0dcea0 --- /dev/null +++ b/third_party/libassimp/contrib/stb_image/stb_image.h @@ -0,0 +1,7462 @@ +/* stb_image - v2.19 - public domain image loader - http://nothings.org/stb + no warranty implied; use at your own risk + + Do this: + #define STB_IMAGE_IMPLEMENTATION + before you include this file in *one* C or C++ file to create the implementation. + + // i.e. it should look like this: + #include ... + #include ... + #include ... + #define STB_IMAGE_IMPLEMENTATION + #include "stb_image.h" + + You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. + And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free + + + QUICK NOTES: + Primarily of interest to game developers and other people who can + avoid problematic images and only need the trivial interface + + JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) + PNG 1/2/4/8/16-bit-per-channel + + TGA (not sure what subset, if a subset) + BMP non-1bpp, non-RLE + PSD (composited view only, no extra channels, 8/16 bit-per-channel) + + GIF (*comp always reports as 4-channel) + HDR (radiance rgbE format) + PIC (Softimage PIC) + PNM (PPM and PGM binary only) + + Animated GIF still needs a proper API, but here's one way to do it: + http://gist.github.com/urraka/685d9a6340b26b830d49 + + - decode from memory or through FILE (define STBI_NO_STDIO to remove code) + - decode from arbitrary I/O callbacks + - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON) + + Full documentation under "DOCUMENTATION" below. + + +LICENSE + + See end of file for license information. + +RECENT REVISION HISTORY: + + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings + 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes + 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 + RGB-format JPEG; remove white matting in PSD; + allocate large structures on the stack; + correct channel count for PNG & BMP + 2.10 (2016-01-22) avoid warning introduced in 2.09 + 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED + + See end of file for full revision history. + + + ============================ Contributors ========================= + + Image formats Extensions, features + Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) + Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) + Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) + Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) + Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) + Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) + Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) + github:urraka (animated gif) Junggon Kim (PNM comments) + Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA) + socks-the-fox (16-bit PNG) + Jeremy Sawicki (handle all ImageNet JPGs) + Optimizations & bugfixes Mikhail Morozov (1-bit BMP) + Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query) + Arseny Kapoulkine + John-Mark Allen + + Bug & warning fixes + Marc LeBlanc David Woo Guillaume George Martins Mozeiko + Christpher Lloyd Jerry Jansson Joseph Thomson Phil Jordan + Dave Moore Roy Eltham Hayaki Saito Nathan Reed + Won Chun Luke Graham Johan Duparc Nick Verigakis + the Horde3D community Thomas Ruf Ronny Chevalier github:rlyeh + Janez Zemva John Bartholomew Michal Cichon github:romigrou + Jonathan Blow Ken Hamada Tero Hanninen github:svdijk + Laurent Gomila Cort Stratton Sergio Gonzalez github:snagar + Aruelien Pocheville Thibault Reuille Cass Everitt github:Zelex + Ryamond Barbiero Paul Du Bois Engin Manap github:grim210 + Aldo Culquicondor Philipp Wiesemann Dale Weiler github:sammyhw + Oriol Ferrer Mesia Josh Tobin Matthew Gregan github:phprus + Julian Raschke Gregory Mullen Baldur Karlsson github:poppolopoppo + Christian Floisand Kevin Schmidt github:darealshinji + Blazej Dariusz Roszkowski github:Michaelangel007 +*/ + +#ifndef STBI_INCLUDE_STB_IMAGE_H +#define STBI_INCLUDE_STB_IMAGE_H + +// DOCUMENTATION +// +// Limitations: +// - no 12-bit-per-channel JPEG +// - no JPEGs with arithmetic coding +// - GIF always returns *comp=4 +// +// Basic usage (see HDR discussion below for HDR usage): +// int x,y,n; +// unsigned char *data = stbi_load(filename, &x, &y, &n, 0); +// // ... process data if not NULL ... +// // ... x = width, y = height, n = # 8-bit components per pixel ... +// // ... replace '0' with '1'..'4' to force that many components per pixel +// // ... but 'n' will always be the number that it would have been if you said 0 +// stbi_image_free(data) +// +// Standard parameters: +// int *x -- outputs image width in pixels +// int *y -- outputs image height in pixels +// int *channels_in_file -- outputs # of image components in image file +// int desired_channels -- if non-zero, # of image components requested in result +// +// The return value from an image loader is an 'unsigned char *' which points +// to the pixel data, or NULL on an allocation failure or if the image is +// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels, +// with each pixel consisting of N interleaved 8-bit components; the first +// pixel pointed to is top-left-most in the image. There is no padding between +// image scanlines or between pixels, regardless of format. The number of +// components N is 'desired_channels' if desired_channels is non-zero, or +// *channels_in_file otherwise. If desired_channels is non-zero, +// *channels_in_file has the number of components that _would_ have been +// output otherwise. E.g. if you set desired_channels to 4, you will always +// get RGBA output, but you can check *channels_in_file to see if it's trivially +// opaque because e.g. there were only 3 channels in the source image. +// +// An output image with N components has the following components interleaved +// in this order in each pixel: +// +// N=#comp components +// 1 grey +// 2 grey, alpha +// 3 red, green, blue +// 4 red, green, blue, alpha +// +// If image loading fails for any reason, the return value will be NULL, +// and *x, *y, *channels_in_file will be unchanged. The function +// stbi_failure_reason() can be queried for an extremely brief, end-user +// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS +// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly +// more user-friendly ones. +// +// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. +// +// =========================================================================== +// +// Philosophy +// +// stb libraries are designed with the following priorities: +// +// 1. easy to use +// 2. easy to maintain +// 3. good performance +// +// Sometimes I let "good performance" creep up in priority over "easy to maintain", +// and for best performance I may provide less-easy-to-use APIs that give higher +// performance, in addition to the easy to use ones. Nevertheless, it's important +// to keep in mind that from the standpoint of you, a client of this library, +// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all. +// +// Some secondary priorities arise directly from the first two, some of which +// make more explicit reasons why performance can't be emphasized. +// +// - Portable ("ease of use") +// - Small source code footprint ("easy to maintain") +// - No dependencies ("ease of use") +// +// =========================================================================== +// +// I/O callbacks +// +// I/O callbacks allow you to read from arbitrary sources, like packaged +// files or some other source. Data read from callbacks are processed +// through a small internal buffer (currently 128 bytes) to try to reduce +// overhead. +// +// The three functions you must define are "read" (reads some bytes of data), +// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). +// +// =========================================================================== +// +// SIMD support +// +// The JPEG decoder will try to automatically use SIMD kernels on x86 when +// supported by the compiler. For ARM Neon support, you must explicitly +// request it. +// +// (The old do-it-yourself SIMD API is no longer supported in the current +// code.) +// +// On x86, SSE2 will automatically be used when available based on a run-time +// test; if not, the generic C versions are used as a fall-back. On ARM targets, +// the typical path is to have separate builds for NEON and non-NEON devices +// (at least this is true for iOS and Android). Therefore, the NEON support is +// toggled by a build flag: define STBI_NEON to get NEON loops. +// +// If for some reason you do not want to use any of SIMD code, or if +// you have issues compiling it, you can disable it entirely by +// defining STBI_NO_SIMD. +// +// =========================================================================== +// +// HDR image support (disable by defining STBI_NO_HDR) +// +// stb_image now supports loading HDR images in general, and currently +// the Radiance .HDR file format, although the support is provided +// generically. You can still load any file through the existing interface; +// if you attempt to load an HDR file, it will be automatically remapped to +// LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; +// both of these constants can be reconfigured through this interface: +// +// stbi_hdr_to_ldr_gamma(2.2f); +// stbi_hdr_to_ldr_scale(1.0f); +// +// (note, do not use _inverse_ constants; stbi_image will invert them +// appropriately). +// +// Additionally, there is a new, parallel interface for loading files as +// (linear) floats to preserve the full dynamic range: +// +// float *data = stbi_loadf(filename, &x, &y, &n, 0); +// +// If you load LDR images through this interface, those images will +// be promoted to floating point values, run through the inverse of +// constants corresponding to the above: +// +// stbi_ldr_to_hdr_scale(1.0f); +// stbi_ldr_to_hdr_gamma(2.2f); +// +// Finally, given a filename (or an open file or memory block--see header +// file for details) containing image data, you can query for the "most +// appropriate" interface to use (that is, whether the image is HDR or +// not), using: +// +// stbi_is_hdr(char *filename); +// +// =========================================================================== +// +// iPhone PNG support: +// +// By default we convert iphone-formatted PNGs back to RGB, even though +// they are internally encoded differently. You can disable this conversion +// by by calling stbi_convert_iphone_png_to_rgb(0), in which case +// you will always just get the native iphone "format" through (which +// is BGR stored in RGB). +// +// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per +// pixel to remove any premultiplied alpha *only* if the image file explicitly +// says there's premultiplied data (currently only happens in iPhone images, +// and only if iPhone convert-to-rgb processing is on). +// +// =========================================================================== +// +// ADDITIONAL CONFIGURATION +// +// - You can suppress implementation of any of the decoders to reduce +// your code footprint by #defining one or more of the following +// symbols before creating the implementation. +// +// STBI_NO_JPEG +// STBI_NO_PNG +// STBI_NO_BMP +// STBI_NO_PSD +// STBI_NO_TGA +// STBI_NO_GIF +// STBI_NO_HDR +// STBI_NO_PIC +// STBI_NO_PNM (.ppm and .pgm) +// +// - You can request *only* certain decoders and suppress all other ones +// (this will be more forward-compatible, as addition of new decoders +// doesn't require you to disable them explicitly): +// +// STBI_ONLY_JPEG +// STBI_ONLY_PNG +// STBI_ONLY_BMP +// STBI_ONLY_PSD +// STBI_ONLY_TGA +// STBI_ONLY_GIF +// STBI_ONLY_HDR +// STBI_ONLY_PIC +// STBI_ONLY_PNM (.ppm and .pgm) +// +// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still +// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB +// + + +#ifndef STBI_NO_STDIO +#include +#endif // STBI_NO_STDIO + +#define STBI_VERSION 1 + +enum +{ + STBI_default = 0, // only used for desired_channels + + STBI_grey = 1, + STBI_grey_alpha = 2, + STBI_rgb = 3, + STBI_rgb_alpha = 4 +}; + +typedef unsigned char stbi_uc; +typedef unsigned short stbi_us; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef STB_IMAGE_STATIC +#define STBIDEF static +#else +#define STBIDEF extern +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// PRIMARY API - works on images of any type +// + +// +// load image by filename, open file, or memory buffer +// + +typedef struct +{ + int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read + void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative + int (*eof) (void *user); // returns nonzero if we are at end of file/data +} stbi_io_callbacks; + +//////////////////////////////////// +// +// 8-bits-per-channel interface +// + +STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels); +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +#endif + + +#ifndef STBI_NO_STDIO +STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +// for stbi_load_from_file, file pointer is left pointing immediately after image +#endif + +//////////////////////////////////// +// +// 16-bits-per-channel interface +// + +STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO +STBIDEF stbi_us *stbi_load_16 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +#endif + +//////////////////////////////////// +// +// float-per-channel interface +// +#ifndef STBI_NO_LINEAR + STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + + #ifndef STBI_NO_STDIO + STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); + #endif +#endif + +#ifndef STBI_NO_HDR + STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); + STBIDEF void stbi_hdr_to_ldr_scale(float scale); +#endif // STBI_NO_HDR + +#ifndef STBI_NO_LINEAR + STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); + STBIDEF void stbi_ldr_to_hdr_scale(float scale); +#endif // STBI_NO_LINEAR + +// stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename); +STBIDEF int stbi_is_hdr_from_file(FILE *f); +#endif // STBI_NO_STDIO + + +// get a VERY brief reason for failure +// NOT THREADSAFE +STBIDEF const char *stbi_failure_reason (void); + +// free the loaded image -- this is just free() +STBIDEF void stbi_image_free (void *retval_from_stbi_load); + +// get image dimensions & components without fully decoding +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len); +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user); + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit (char const *filename); +STBIDEF int stbi_is_16_bit_from_file(FILE *f); +#endif + + + +// for image formats that explicitly notate that they have premultiplied alpha, +// we just return the colors as stored in the file. set this flag to force +// unpremultiplication. results are undefined if the unpremultiply overflow. +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); + +// indicate whether we should process iphone images back to canonical format, +// or just pass them through "as-is" +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); + +// flip the image vertically, so the first pixel in the output array is the bottom left +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); + +// ZLIB client - used by PNG, available for other purposes + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header); +STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + +STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + + +#ifdef __cplusplus +} +#endif + +// +// +//// end header file ///////////////////////////////////////////////////// +#endif // STBI_INCLUDE_STB_IMAGE_H + +#ifdef STB_IMAGE_IMPLEMENTATION + +#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ + || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ + || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ + || defined(STBI_ONLY_ZLIB) + #ifndef STBI_ONLY_JPEG + #define STBI_NO_JPEG + #endif + #ifndef STBI_ONLY_PNG + #define STBI_NO_PNG + #endif + #ifndef STBI_ONLY_BMP + #define STBI_NO_BMP + #endif + #ifndef STBI_ONLY_PSD + #define STBI_NO_PSD + #endif + #ifndef STBI_ONLY_TGA + #define STBI_NO_TGA + #endif + #ifndef STBI_ONLY_GIF + #define STBI_NO_GIF + #endif + #ifndef STBI_ONLY_HDR + #define STBI_NO_HDR + #endif + #ifndef STBI_ONLY_PIC + #define STBI_NO_PIC + #endif + #ifndef STBI_ONLY_PNM + #define STBI_NO_PNM + #endif +#endif + +#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) +#define STBI_NO_ZLIB +#endif + + +#include +#include // ptrdiff_t on osx +#include +#include +#include + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) +#include // ldexp, pow +#endif + +#ifndef STBI_NO_STDIO +#include +#endif + +#ifndef STBI_ASSERT +#include +#define STBI_ASSERT(x) assert(x) +#endif + + +#ifndef _MSC_VER + #ifdef __cplusplus + #define stbi_inline inline + #else + #define stbi_inline + #endif +#else + #define stbi_inline __forceinline +#endif + + +#ifdef _MSC_VER +typedef unsigned short stbi__uint16; +typedef signed short stbi__int16; +typedef unsigned int stbi__uint32; +typedef signed int stbi__int32; +#else +#include +typedef uint16_t stbi__uint16; +typedef int16_t stbi__int16; +typedef uint32_t stbi__uint32; +typedef int32_t stbi__int32; +#endif + +// should produce compiler error if size is wrong +typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; + +#ifdef _MSC_VER +#define STBI_NOTUSED(v) (void)(v) +#else +#define STBI_NOTUSED(v) (void)sizeof(v) +#endif + +#ifdef _MSC_VER +#define STBI_HAS_LROTL +#endif + +#ifdef STBI_HAS_LROTL + #define stbi_lrot(x,y) _lrotl(x,y) +#else + #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y)))) +#endif + +#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) +// ok +#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) +// ok +#else +#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." +#endif + +#ifndef STBI_MALLOC +#define STBI_MALLOC(sz) malloc(sz) +#define STBI_REALLOC(p,newsz) realloc(p,newsz) +#define STBI_FREE(p) free(p) +#endif + +#ifndef STBI_REALLOC_SIZED +#define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz) +#endif + +// x86/x64 detection +#if defined(__x86_64__) || defined(_M_X64) +#define STBI__X64_TARGET +#elif defined(__i386) || defined(_M_IX86) +#define STBI__X86_TARGET +#endif + +#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) +// gcc doesn't support sse2 intrinsics unless you compile with -msse2, +// which in turn means it gets to use SSE2 everywhere. This is unfortunate, +// but previous attempts to provide the SSE2 functions with runtime +// detection caused numerous issues. The way architecture extensions are +// exposed in GCC/Clang is, sadly, not really suited for one-file libs. +// New behavior: if compiled with -msse2, we use SSE2 without any +// detection; if not, we don't use it at all. +#define STBI_NO_SIMD +#endif + +#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) +// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET +// +// 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the +// Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant. +// As a result, enabling SSE2 on 32-bit MinGW is dangerous when not +// simultaneously enabling "-mstackrealign". +// +// See https://github.com/nothings/stb/issues/81 for more information. +// +// So default to no SSE2 on 32-bit MinGW. If you've read this far and added +// -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2. +#define STBI_NO_SIMD +#endif + +#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) +#define STBI_SSE2 +#include + +#ifdef _MSC_VER + +#if _MSC_VER >= 1400 // not VC6 +#include // __cpuid +static int stbi__cpuid3(void) +{ + int info[4]; + __cpuid(info,1); + return info[3]; +} +#else +static int stbi__cpuid3(void) +{ + int res; + __asm { + mov eax,1 + cpuid + mov res,edx + } + return res; +} +#endif + +#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name + +static int stbi__sse2_available(void) +{ + int info3 = stbi__cpuid3(); + return ((info3 >> 26) & 1) != 0; +} +#else // assume GCC-style if not VC++ +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) + +static int stbi__sse2_available(void) +{ + // If we're even attempting to compile this on GCC/Clang, that means + // -msse2 is on, which means the compiler is allowed to use SSE2 + // instructions at will, and so are we. + return 1; +} +#endif +#endif + +// ARM NEON +#if defined(STBI_NO_SIMD) && defined(STBI_NEON) +#undef STBI_NEON +#endif + +#ifdef STBI_NEON +#include +// assume GCC or Clang on ARM targets +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) +#endif + +#ifndef STBI_SIMD_ALIGN +#define STBI_SIMD_ALIGN(type, name) type name +#endif + +/////////////////////////////////////////////// +// +// stbi__context struct and start_xxx functions + +// stbi__context structure is our basic context used by all images, so it +// contains all the IO context, plus some basic image information +typedef struct +{ + stbi__uint32 img_x, img_y; + int img_n, img_out_n; + + stbi_io_callbacks io; + void *io_user_data; + + int read_from_callbacks; + int buflen; + stbi_uc buffer_start[128]; + + stbi_uc *img_buffer, *img_buffer_end; + stbi_uc *img_buffer_original, *img_buffer_original_end; +} stbi__context; + + +static void stbi__refill_buffer(stbi__context *s); + +// initialize a memory-decode context +static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) +{ + s->io.read = NULL; + s->read_from_callbacks = 0; + s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer; + s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len; +} + +// initialize a callback-based context +static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user) +{ + s->io = *c; + s->io_user_data = user; + s->buflen = sizeof(s->buffer_start); + s->read_from_callbacks = 1; + s->img_buffer_original = s->buffer_start; + stbi__refill_buffer(s); + s->img_buffer_original_end = s->img_buffer_end; +} + +#ifndef STBI_NO_STDIO + +static int stbi__stdio_read(void *user, char *data, int size) +{ + return (int) fread(data,1,size,(FILE*) user); +} + +static void stbi__stdio_skip(void *user, int n) +{ + fseek((FILE*) user, n, SEEK_CUR); +} + +static int stbi__stdio_eof(void *user) +{ + return feof((FILE*) user); +} + +static stbi_io_callbacks stbi__stdio_callbacks = +{ + stbi__stdio_read, + stbi__stdio_skip, + stbi__stdio_eof, +}; + +static void stbi__start_file(stbi__context *s, FILE *f) +{ + stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f); +} + +//static void stop_file(stbi__context *s) { } + +#endif // !STBI_NO_STDIO + +static void stbi__rewind(stbi__context *s) +{ + // conceptually rewind SHOULD rewind to the beginning of the stream, + // but we just rewind to the beginning of the initial buffer, because + // we only use it after doing 'test', which only ever looks at at most 92 bytes + s->img_buffer = s->img_buffer_original; + s->img_buffer_end = s->img_buffer_original_end; +} + +enum +{ + STBI_ORDER_RGB, + STBI_ORDER_BGR +}; + +typedef struct +{ + int bits_per_channel; + int num_channels; + int channel_order; +} stbi__result_info; + +#ifndef STBI_NO_JPEG +static int stbi__jpeg_test(stbi__context *s); +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNG +static int stbi__png_test(stbi__context *s); +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__png_is16(stbi__context *s); +#endif + +#ifndef STBI_NO_BMP +static int stbi__bmp_test(stbi__context *s); +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_TGA +static int stbi__tga_test(stbi__context *s); +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s); +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc); +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__psd_is16(stbi__context *s); +#endif + +#ifndef STBI_NO_HDR +static int stbi__hdr_test(stbi__context *s); +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_test(stbi__context *s); +static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_GIF +static int stbi__gif_test(stbi__context *s); +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNM +static int stbi__pnm_test(stbi__context *s); +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +// this is not threadsafe +static const char *stbi__g_failure_reason; + +STBIDEF const char *stbi_failure_reason(void) +{ + return stbi__g_failure_reason; +} + +static int stbi__err(const char *str) +{ + stbi__g_failure_reason = str; + return 0; +} + +static void *stbi__malloc(size_t size) +{ + return STBI_MALLOC(size); +} + +// stb_image uses ints pervasively, including for offset calculations. +// therefore the largest decoded image size we can support with the +// current code, even on 64-bit targets, is INT_MAX. this is not a +// significant limitation for the intended use case. +// +// we do, however, need to make sure our size calculations don't +// overflow. hence a few helper functions for size calculations that +// multiply integers together, making sure that they're non-negative +// and no overflow occurs. + +// return 1 if the sum is valid, 0 on overflow. +// negative terms are considered invalid. +static int stbi__addsizes_valid(int a, int b) +{ + if (b < 0) return 0; + // now 0 <= b <= INT_MAX, hence also + // 0 <= INT_MAX - b <= INTMAX. + // And "a + b <= INT_MAX" (which might overflow) is the + // same as a <= INT_MAX - b (no overflow) + return a <= INT_MAX - b; +} + +// returns 1 if the product is valid, 0 on overflow. +// negative factors are considered invalid. +static int stbi__mul2sizes_valid(int a, int b) +{ + if (a < 0 || b < 0) return 0; + if (b == 0) return 1; // mul-by-0 is always safe + // portable way to check for no overflows in a*b + return a <= INT_MAX/b; +} + +// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow +static int stbi__mad2sizes_valid(int a, int b, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add); +} + +// returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow +static int stbi__mad3sizes_valid(int a, int b, int c, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__addsizes_valid(a*b*c, add); +} + +// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) +static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add); +} +#endif + +// mallocs with size overflow checking +static void *stbi__malloc_mad2(int a, int b, int add) +{ + if (!stbi__mad2sizes_valid(a, b, add)) return NULL; + return stbi__malloc(a*b + add); +} + +static void *stbi__malloc_mad3(int a, int b, int c, int add) +{ + if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; + return stbi__malloc(a*b*c + add); +} + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) +static void *stbi__malloc_mad4(int a, int b, int c, int d, int add) +{ + if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; + return stbi__malloc(a*b*c*d + add); +} +#endif + +// stbi__err - error +// stbi__errpf - error returning pointer to float +// stbi__errpuc - error returning pointer to unsigned char + +#ifdef STBI_NO_FAILURE_STRINGS + #define stbi__err(x,y) 0 +#elif defined(STBI_FAILURE_USERMSG) + #define stbi__err(x,y) stbi__err(y) +#else + #define stbi__err(x,y) stbi__err(x) +#endif + +#define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL)) +#define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL)) + +STBIDEF void stbi_image_free(void *retval_from_stbi_load) +{ + STBI_FREE(retval_from_stbi_load); +} + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); +#endif + +#ifndef STBI_NO_HDR +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); +#endif + +static int stbi__vertically_flip_on_load = 0; + +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load = flag_true_if_should_flip; +} + +static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields + ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed + ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order + ri->num_channels = 0; + + #ifndef STBI_NO_JPEG + if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_PNG + if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_BMP + if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_GIF + if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_PSD + if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc); + #endif + #ifndef STBI_NO_PIC + if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_PNM + if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri); + #endif + + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri); + return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); + } + #endif + + #ifndef STBI_NO_TGA + // test tga last because it's a crappy test! + if (stbi__tga_test(s)) + return stbi__tga_load(s,x,y,comp,req_comp, ri); + #endif + + return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); +} + +static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi_uc *reduced; + + reduced = (stbi_uc *) stbi__malloc(img_len); + if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling + + STBI_FREE(orig); + return reduced; +} + +static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi__uint16 *enlarged; + + enlarged = (stbi__uint16 *) stbi__malloc(img_len*2); + if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff + + STBI_FREE(orig); + return enlarged; +} + +static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) +{ + int row; + size_t bytes_per_row = (size_t)w * bytes_per_pixel; + stbi_uc temp[2048]; + stbi_uc *bytes = (stbi_uc *)image; + + for (row = 0; row < (h>>1); row++) { + stbi_uc *row0 = bytes + row*bytes_per_row; + stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row; + // swap row0 with row1 + size_t bytes_left = bytes_per_row; + while (bytes_left) { + size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); + memcpy(temp, row0, bytes_copy); + memcpy(row0, row1, bytes_copy); + memcpy(row1, temp, bytes_copy); + row0 += bytes_copy; + row1 += bytes_copy; + bytes_left -= bytes_copy; + } + } +} + +static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel) +{ + int slice; + int slice_size = w * h * bytes_per_pixel; + + stbi_uc *bytes = (stbi_uc *)image; + for (slice = 0; slice < z; ++slice) { + stbi__vertical_flip(bytes, w, h, bytes_per_pixel); + bytes += slice_size; + } +} + +static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); + + if (result == NULL) + return NULL; + + if (ri.bits_per_channel != 8) { + STBI_ASSERT(ri.bits_per_channel == 16); + result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 8; + } + + // @TODO: move stbi__convert_format to here + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); + } + + return (unsigned char *) result; +} + +static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); + + if (result == NULL) + return NULL; + + if (ri.bits_per_channel != 16) { + STBI_ASSERT(ri.bits_per_channel == 8); + result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 16; + } + + // @TODO: move stbi__convert_format16 to here + // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); + } + + return (stbi__uint16 *) result; +} + +#if !defined(STBI_NO_HDR) || !defined(STBI_NO_LINEAR) +static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) +{ + if (stbi__vertically_flip_on_load && result != NULL) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); + } +} +#endif + +#ifndef STBI_NO_STDIO + +static FILE *stbi__fopen(char const *filename, char const *mode) +{ + FILE *f; +#if defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != fopen_s(&f, filename, mode)) + f=0; +#else + f = fopen(filename, mode); +#endif + return f; +} + + +STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + unsigned char *result; + if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__uint16 *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + stbi__uint16 *result; + if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file_16(f,x,y,comp,req_comp); + fclose(f); + return result; +} + + +#endif //!STBI_NO_STDIO + +STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + +STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); +} + +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_mem(&s,buffer,len); + + result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); + if (stbi__vertically_flip_on_load) { + stbi__vertical_flip_slices( result, *x, *y, *z, *comp ); + } + + return result; +} +#endif + +#ifndef STBI_NO_LINEAR +static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *data; + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + stbi__result_info ri; + float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri); + if (hdr_data) + stbi__float_postprocess(hdr_data,x,y,comp,req_comp); + return hdr_data; + } + #endif + data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); + if (data) + return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); + return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); +} + +STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} + +STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_STDIO +STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + float *result; + FILE *f = stbi__fopen(filename, "rb"); + if (!f) return stbi__errpf("can't fopen", "Unable to open file"); + result = stbi_loadf_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_file(&s,f); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} +#endif // !STBI_NO_STDIO + +#endif // !STBI_NO_LINEAR + +// these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is +// defined, for API simplicity; if STBI_NO_LINEAR is defined, it always +// reports false! + +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(buffer); + STBI_NOTUSED(len); + return 0; + #endif +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result=0; + if (f) { + result = stbi_is_hdr_from_file(f); + fclose(f); + } + return result; +} + +STBIDEF int stbi_is_hdr_from_file(FILE *f) +{ + #ifndef STBI_NO_HDR + long pos = ftell(f); + int res; + stbi__context s; + stbi__start_file(&s,f); + res = stbi__hdr_test(&s); + fseek(f, pos, SEEK_SET); + return res; + #else + STBI_NOTUSED(f); + return 0; + #endif +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(clbk); + STBI_NOTUSED(user); + return 0; + #endif +} + +#ifndef STBI_NO_LINEAR +static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f; + +STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } +STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } +#endif + +static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; + +STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; } +STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; } + + +////////////////////////////////////////////////////////////////////////////// +// +// Common code used by all image loaders +// + +enum +{ + STBI__SCAN_load=0, + STBI__SCAN_type, + STBI__SCAN_header +}; + +static void stbi__refill_buffer(stbi__context *s) +{ + int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); + if (n == 0) { + // at end of file, treat same as if from memory, but need to handle case + // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file + s->read_from_callbacks = 0; + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start+1; + *s->img_buffer = 0; + } else { + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start + n; + } +} + +stbi_inline static stbi_uc stbi__get8(stbi__context *s) +{ + if (s->img_buffer < s->img_buffer_end) + return *s->img_buffer++; + if (s->read_from_callbacks) { + stbi__refill_buffer(s); + return *s->img_buffer++; + } + return 0; +} + +stbi_inline static int stbi__at_eof(stbi__context *s) +{ + if (s->io.read) { + if (!(s->io.eof)(s->io_user_data)) return 0; + // if feof() is true, check if buffer = end + // special case: we've only got the special 0 character at the end + if (s->read_from_callbacks == 0) return 1; + } + + return s->img_buffer >= s->img_buffer_end; +} + +static void stbi__skip(stbi__context *s, int n) +{ + if (n < 0) { + s->img_buffer = s->img_buffer_end; + return; + } + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + s->img_buffer = s->img_buffer_end; + (s->io.skip)(s->io_user_data, n - blen); + return; + } + } + s->img_buffer += n; +} + +static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) +{ + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + int res, count; + + memcpy(buffer, s->img_buffer, blen); + + count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen); + res = (count == (n-blen)); + s->img_buffer = s->img_buffer_end; + return res; + } + } + + if (s->img_buffer+n <= s->img_buffer_end) { + memcpy(buffer, s->img_buffer, n); + s->img_buffer += n; + return 1; + } else + return 0; +} + +static int stbi__get16be(stbi__context *s) +{ + int z = stbi__get8(s); + return (z << 8) + stbi__get8(s); +} + +static stbi__uint32 stbi__get32be(stbi__context *s) +{ + stbi__uint32 z = stbi__get16be(s); + return (z << 16) + stbi__get16be(s); +} + +#if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) +// nothing +#else +static int stbi__get16le(stbi__context *s) +{ + int z = stbi__get8(s); + return z + (stbi__get8(s) << 8); +} +#endif + +#ifndef STBI_NO_BMP +static stbi__uint32 stbi__get32le(stbi__context *s) +{ + stbi__uint32 z = stbi__get16le(s); + return z + (stbi__get16le(s) << 16); +} +#endif + +#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings + + +////////////////////////////////////////////////////////////////////////////// +// +// generic converter from built-in img_n to req_comp +// individual types do this automatically as much as possible (e.g. jpeg +// does all cases internally since it needs to colorspace convert anyway, +// and it never has alpha, so very few cases ). png can automatically +// interleave an alpha=255 channel, but falls back to this for other cases +// +// assume data buffer is malloced, so malloc a new one and free that one +// only failure mode is malloc failing + +static stbi_uc stbi__compute_y(int r, int g, int b) +{ + return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8); +} + +static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + unsigned char *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0); + if (good == NULL) { + STBI_FREE(data); + return stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + unsigned char *src = data + j * x * img_n ; + unsigned char *dest = good + j * x * req_comp; + + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0], dest[1]=255; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = 255; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; } break; + default: STBI_ASSERT(0); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} + +static stbi__uint16 stbi__compute_y_16(int r, int g, int b) +{ + return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8); +} + +static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + stbi__uint16 *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2); + if (good == NULL) { + STBI_FREE(data); + return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + stbi__uint16 *src = data + j * x * img_n ; + stbi__uint16 *dest = good + j * x * req_comp; + + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0], dest[1]=0xffff; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0], dest[3]=0xffff; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=0xffff; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]), dest[1] = 0xffff; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]), dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; } break; + default: STBI_ASSERT(0); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) +{ + int i,k,n; + float *output; + if (!data) return NULL; + output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale); + } + if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f; + } + STBI_FREE(data); + return output; +} +#endif + +#ifndef STBI_NO_HDR +#define stbi__float2int(x) ((int) (x)) +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) +{ + int i,k,n; + stbi_uc *output; + if (!data) return NULL; + output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + if (k < comp) { + float z = data[i*comp+k] * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + } + STBI_FREE(data); + return output; +} +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// "baseline" JPEG/JFIF decoder +// +// simple implementation +// - doesn't support delayed output of y-dimension +// - simple interface (only one output format: 8-bit interleaved RGB) +// - doesn't try to recover corrupt jpegs +// - doesn't allow partial loading, loading multiple at once +// - still fast on x86 (copying globals into locals doesn't help x86) +// - allocates lots of intermediate memory (full size of all components) +// - non-interleaved case requires this anyway +// - allows good upsampling (see next) +// high-quality +// - upsampled channels are bilinearly interpolated, even across blocks +// - quality integer IDCT derived from IJG's 'slow' +// performance +// - fast huffman; reasonable integer IDCT +// - some SIMD kernels for common paths on targets with SSE2/NEON +// - uses a lot of intermediate memory, could cache poorly + +#ifndef STBI_NO_JPEG + +// huffman decoding acceleration +#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache + +typedef struct +{ + stbi_uc fast[1 << FAST_BITS]; + // weirdly, repacking this into AoS is a 10% speed loss, instead of a win + stbi__uint16 code[256]; + stbi_uc values[256]; + stbi_uc size[257]; + unsigned int maxcode[18]; + int delta[17]; // old 'firstsymbol' - old 'firstcode' +} stbi__huffman; + +typedef struct +{ + stbi__context *s; + stbi__huffman huff_dc[4]; + stbi__huffman huff_ac[4]; + stbi__uint16 dequant[4][64]; + stbi__int16 fast_ac[4][1 << FAST_BITS]; + +// sizes for components, interleaved MCUs + int img_h_max, img_v_max; + int img_mcu_x, img_mcu_y; + int img_mcu_w, img_mcu_h; + +// definition of jpeg image component + struct + { + int id; + int h,v; + int tq; + int hd,ha; + int dc_pred; + + int x,y,w2,h2; + stbi_uc *data; + void *raw_data, *raw_coeff; + stbi_uc *linebuf; + short *coeff; // progressive only + int coeff_w, coeff_h; // number of 8x8 coefficient blocks + } img_comp[4]; + + stbi__uint32 code_buffer; // jpeg entropy-coded buffer + int code_bits; // number of valid bits + unsigned char marker; // marker seen while filling entropy buffer + int nomore; // flag if we saw a marker so must stop + + int progressive; + int spec_start; + int spec_end; + int succ_high; + int succ_low; + int eob_run; + int jfif; + int app14_color_transform; // Adobe APP14 tag + int rgb; + + int scan_n, order[4]; + int restart_interval, todo; + +// kernels + void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]); + void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step); + stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs); +} stbi__jpeg; + +static int stbi__build_huffman(stbi__huffman *h, int *count) +{ + int i,j,k=0; + unsigned int code; + // build size list for each symbol (from JPEG spec) + for (i=0; i < 16; ++i) + for (j=0; j < count[i]; ++j) + h->size[k++] = (stbi_uc) (i+1); + h->size[k] = 0; + + // compute actual symbols (from jpeg spec) + code = 0; + k = 0; + for(j=1; j <= 16; ++j) { + // compute delta to add to code to compute symbol id + h->delta[j] = k - code; + if (h->size[k] == j) { + while (h->size[k] == j) + h->code[k++] = (stbi__uint16) (code++); + if (code-1 >= (1u << j)) return stbi__err("bad code lengths","Corrupt JPEG"); + } + // compute largest code + 1 for this size, preshifted as needed later + h->maxcode[j] = code << (16-j); + code <<= 1; + } + h->maxcode[j] = 0xffffffff; + + // build non-spec acceleration table; 255 is flag for not-accelerated + memset(h->fast, 255, 1 << FAST_BITS); + for (i=0; i < k; ++i) { + int s = h->size[i]; + if (s <= FAST_BITS) { + int c = h->code[i] << (FAST_BITS-s); + int m = 1 << (FAST_BITS-s); + for (j=0; j < m; ++j) { + h->fast[c+j] = (stbi_uc) i; + } + } + } + return 1; +} + +// build a table that decodes both magnitude and value of small ACs in +// one go. +static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) +{ + int i; + for (i=0; i < (1 << FAST_BITS); ++i) { + stbi_uc fast = h->fast[i]; + fast_ac[i] = 0; + if (fast < 255) { + int rs = h->values[fast]; + int run = (rs >> 4) & 15; + int magbits = rs & 15; + int len = h->size[fast]; + + if (magbits && len + magbits <= FAST_BITS) { + // magnitude code followed by receive_extend code + int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); + int m = 1 << (magbits - 1); + if (k < m) k += (~0U << magbits) + 1; + // if the result is small enough, we can fit it in fast_ac table + if (k >= -128 && k <= 127) + fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits)); + } + } + } +} + +static void stbi__grow_buffer_unsafe(stbi__jpeg *j) +{ + do { + unsigned int b = j->nomore ? 0 : stbi__get8(j->s); + if (b == 0xff) { + int c = stbi__get8(j->s); + while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes + if (c != 0) { + j->marker = (unsigned char) c; + j->nomore = 1; + return; + } + } + j->code_buffer |= b << (24 - j->code_bits); + j->code_bits += 8; + } while (j->code_bits <= 24); +} + +// (1 << n) - 1 +static const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; + +// decode a jpeg huffman value from the bitstream +stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) +{ + unsigned int temp; + int c,k; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + // look at the top FAST_BITS and determine what symbol ID it is, + // if the code is <= FAST_BITS + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + k = h->fast[c]; + if (k < 255) { + int s = h->size[k]; + if (s > j->code_bits) + return -1; + j->code_buffer <<= s; + j->code_bits -= s; + return h->values[k]; + } + + // naive test is to shift the code_buffer down so k bits are + // valid, then test against maxcode. To speed this up, we've + // preshifted maxcode left so that it has (16-k) 0s at the + // end; in other words, regardless of the number of bits, it + // wants to be compared against something shifted to have 16; + // that way we don't need to shift inside the loop. + temp = j->code_buffer >> 16; + for (k=FAST_BITS+1 ; ; ++k) + if (temp < h->maxcode[k]) + break; + if (k == 17) { + // error! code not found + j->code_bits -= 16; + return -1; + } + + if (k > j->code_bits) + return -1; + + // convert the huffman code to the symbol id + c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; + STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); + + // convert the id to a symbol + j->code_bits -= k; + j->code_buffer <<= k; + return h->values[c]; +} + +// bias[n] = (-1<code_bits < n) stbi__grow_buffer_unsafe(j); + + sgn = (stbi__int32)j->code_buffer >> 31; // sign bit is always in MSB + k = stbi_lrot(j->code_buffer, n); + STBI_ASSERT(n >= 0 && n < (int) (sizeof(stbi__bmask)/sizeof(*stbi__bmask))); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k + (stbi__jbias[n] & ~sgn); +} + +// get some unsigned bits +stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) +{ + unsigned int k; + if (j->code_bits < n) stbi__grow_buffer_unsafe(j); + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k; +} + +stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) +{ + unsigned int k; + if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); + k = j->code_buffer; + j->code_buffer <<= 1; + --j->code_bits; + return k & 0x80000000; +} + +// given a value that's at position X in the zigzag stream, +// where does it appear in the 8x8 matrix coded as row-major? +static const stbi_uc stbi__jpeg_dezigzag[64+15] = +{ + 0, 1, 8, 16, 9, 2, 3, 10, + 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, + 53, 60, 61, 54, 47, 55, 62, 63, + // let corrupt input sample past end + 63, 63, 63, 63, 63, 63, 63, 63, + 63, 63, 63, 63, 63, 63, 63 +}; + +// decode one 64-entry block-- +static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant) +{ + int diff,dc,k; + int t; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + + // 0 all the ac values now so we can do it 32-bits at a time + memset(data,0,64*sizeof(data[0])); + + diff = t ? stbi__extend_receive(j, t) : 0; + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + data[0] = (short) (dc * dequant[0]); + + // decode AC components, see JPEG spec + k = 1; + do { + unsigned int zig; + int c,r,s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + j->code_buffer <<= s; + j->code_bits -= s; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) ((r >> 8) * dequant[zig]); + } else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (rs != 0xf0) break; // end block + k += 16; + } else { + k += r; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]); + } + } + } while (k < 64); + return 1; +} + +static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b) +{ + int diff,dc; + int t; + if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + if (j->succ_high == 0) { + // first scan for DC coefficient, must be first + memset(data,0,64*sizeof(data[0])); // 0 all the ac values now + t = stbi__jpeg_huff_decode(j, hdc); + diff = t ? stbi__extend_receive(j, t) : 0; + + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + data[0] = (short) (dc << j->succ_low); + } else { + // refinement scan for DC coefficient + if (stbi__jpeg_get_bit(j)) + data[0] += (short) (1 << j->succ_low); + } + return 1; +} + +// @OPTIMIZE: store non-zigzagged during the decode passes, +// and only de-zigzag when dequantizing +static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac) +{ + int k; + if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->succ_high == 0) { + int shift = j->succ_low; + + if (j->eob_run) { + --j->eob_run; + return 1; + } + + k = j->spec_start; + do { + unsigned int zig; + int c,r,s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + j->code_buffer <<= s; + j->code_bits -= s; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) ((r >> 8) << shift); + } else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r); + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + --j->eob_run; + break; + } + k += 16; + } else { + k += r; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) (stbi__extend_receive(j,s) << shift); + } + } + } while (k <= j->spec_end); + } else { + // refinement scan for these AC coefficients + + short bit = (short) (1 << j->succ_low); + + if (j->eob_run) { + --j->eob_run; + for (k = j->spec_start; k <= j->spec_end; ++k) { + short *p = &data[stbi__jpeg_dezigzag[k]]; + if (*p != 0) + if (stbi__jpeg_get_bit(j)) + if ((*p & bit)==0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } + } else { + k = j->spec_start; + do { + int r,s; + int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r) - 1; + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + r = 64; // force end of block + } else { + // r=15 s=0 should write 16 0s, so we just do + // a run of 15 0s and then write s (which is 0), + // so we don't have to do anything special here + } + } else { + if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); + // sign bit + if (stbi__jpeg_get_bit(j)) + s = bit; + else + s = -bit; + } + + // advance by r + while (k <= j->spec_end) { + short *p = &data[stbi__jpeg_dezigzag[k++]]; + if (*p != 0) { + if (stbi__jpeg_get_bit(j)) + if ((*p & bit)==0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } else { + if (r == 0) { + *p = (short) s; + break; + } + --r; + } + } + } while (k <= j->spec_end); + } + } + return 1; +} + +// take a -128..127 value and stbi__clamp it and convert to 0..255 +stbi_inline static stbi_uc stbi__clamp(int x) +{ + // trick to use a single test to catch both cases + if ((unsigned int) x > 255) { + if (x < 0) return 0; + if (x > 255) return 255; + } + return (stbi_uc) x; +} + +#define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) +#define stbi__fsh(x) ((x) * 4096) + +// derived from jidctint -- DCT_ISLOW +#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ + int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ + p2 = s2; \ + p3 = s6; \ + p1 = (p2+p3) * stbi__f2f(0.5411961f); \ + t2 = p1 + p3*stbi__f2f(-1.847759065f); \ + t3 = p1 + p2*stbi__f2f( 0.765366865f); \ + p2 = s0; \ + p3 = s4; \ + t0 = stbi__fsh(p2+p3); \ + t1 = stbi__fsh(p2-p3); \ + x0 = t0+t3; \ + x3 = t0-t3; \ + x1 = t1+t2; \ + x2 = t1-t2; \ + t0 = s7; \ + t1 = s5; \ + t2 = s3; \ + t3 = s1; \ + p3 = t0+t2; \ + p4 = t1+t3; \ + p1 = t0+t3; \ + p2 = t1+t2; \ + p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ + t0 = t0*stbi__f2f( 0.298631336f); \ + t1 = t1*stbi__f2f( 2.053119869f); \ + t2 = t2*stbi__f2f( 3.072711026f); \ + t3 = t3*stbi__f2f( 1.501321110f); \ + p1 = p5 + p1*stbi__f2f(-0.899976223f); \ + p2 = p5 + p2*stbi__f2f(-2.562915447f); \ + p3 = p3*stbi__f2f(-1.961570560f); \ + p4 = p4*stbi__f2f(-0.390180644f); \ + t3 += p1+p4; \ + t2 += p2+p3; \ + t1 += p2+p4; \ + t0 += p1+p3; + +static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) +{ + int i,val[64],*v=val; + stbi_uc *o; + short *d = data; + + // columns + for (i=0; i < 8; ++i,++d, ++v) { + // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing + if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 + && d[40]==0 && d[48]==0 && d[56]==0) { + // no shortcut 0 seconds + // (1|2|3|4|5|6|7)==0 0 seconds + // all separate -0.047 seconds + // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds + int dcterm = d[0]*4; + v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; + } else { + STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56]) + // constants scaled things up by 1<<12; let's bring them back + // down, but keep 2 extra bits of precision + x0 += 512; x1 += 512; x2 += 512; x3 += 512; + v[ 0] = (x0+t3) >> 10; + v[56] = (x0-t3) >> 10; + v[ 8] = (x1+t2) >> 10; + v[48] = (x1-t2) >> 10; + v[16] = (x2+t1) >> 10; + v[40] = (x2-t1) >> 10; + v[24] = (x3+t0) >> 10; + v[32] = (x3-t0) >> 10; + } + } + + for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { + // no fast case since the first 1D IDCT spread components out + STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) + // constants scaled things up by 1<<12, plus we had 1<<2 from first + // loop, plus horizontal and vertical each scale by sqrt(8) so together + // we've got an extra 1<<3, so 1<<17 total we need to remove. + // so we want to round that, which means adding 0.5 * 1<<17, + // aka 65536. Also, we'll end up with -128 to 127 that we want + // to encode as 0..255 by adding 128, so we'll add that before the shift + x0 += 65536 + (128<<17); + x1 += 65536 + (128<<17); + x2 += 65536 + (128<<17); + x3 += 65536 + (128<<17); + // tried computing the shifts into temps, or'ing the temps to see + // if any were out of range, but that was slower + o[0] = stbi__clamp((x0+t3) >> 17); + o[7] = stbi__clamp((x0-t3) >> 17); + o[1] = stbi__clamp((x1+t2) >> 17); + o[6] = stbi__clamp((x1-t2) >> 17); + o[2] = stbi__clamp((x2+t1) >> 17); + o[5] = stbi__clamp((x2-t1) >> 17); + o[3] = stbi__clamp((x3+t0) >> 17); + o[4] = stbi__clamp((x3-t0) >> 17); + } +} + +#ifdef STBI_SSE2 +// sse2 integer IDCT. not the fastest possible implementation but it +// produces bit-identical results to the generic C version so it's +// fully "transparent". +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + // This is constructed to match our regular (generic) integer IDCT exactly. + __m128i row0, row1, row2, row3, row4, row5, row6, row7; + __m128i tmp; + + // dot product constant: even elems=x, odd elems=y + #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y)) + + // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) + // out(1) = c1[even]*x + c1[odd]*y + #define dct_rot(out0,out1, x,y,c0,c1) \ + __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \ + __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \ + __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ + __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ + __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ + __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) + + // out = in << 12 (in 16-bit, out 32-bit) + #define dct_widen(out, in) \ + __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ + __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) + + // wide add + #define dct_wadd(out, a, b) \ + __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_add_epi32(a##_h, b##_h) + + // wide sub + #define dct_wsub(out, a, b) \ + __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) + + // butterfly a/b, add bias, then shift by "s" and pack + #define dct_bfly32o(out0, out1, a,b,bias,s) \ + { \ + __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ + __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ + dct_wadd(sum, abiased, b); \ + dct_wsub(dif, abiased, b); \ + out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ + out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ + } + + // 8-bit interleave step (for transposes) + #define dct_interleave8(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi8(a, b); \ + b = _mm_unpackhi_epi8(tmp, b) + + // 16-bit interleave step (for transposes) + #define dct_interleave16(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi16(a, b); \ + b = _mm_unpackhi_epi16(tmp, b) + + #define dct_pass(bias,shift) \ + { \ + /* even part */ \ + dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \ + __m128i sum04 = _mm_add_epi16(row0, row4); \ + __m128i dif04 = _mm_sub_epi16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \ + dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \ + __m128i sum17 = _mm_add_epi16(row1, row7); \ + __m128i sum35 = _mm_add_epi16(row3, row5); \ + dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \ + dct_wadd(x4, y0o, y4o); \ + dct_wadd(x5, y1o, y5o); \ + dct_wadd(x6, y2o, y5o); \ + dct_wadd(x7, y3o, y4o); \ + dct_bfly32o(row0,row7, x0,x7,bias,shift); \ + dct_bfly32o(row1,row6, x1,x6,bias,shift); \ + dct_bfly32o(row2,row5, x2,x5,bias,shift); \ + dct_bfly32o(row3,row4, x3,x4,bias,shift); \ + } + + __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); + __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f)); + __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f)); + __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); + __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f)); + __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f)); + __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f)); + __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f)); + + // rounding biases in column/row passes, see stbi__idct_block for explanation. + __m128i bias_0 = _mm_set1_epi32(512); + __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17)); + + // load + row0 = _mm_load_si128((const __m128i *) (data + 0*8)); + row1 = _mm_load_si128((const __m128i *) (data + 1*8)); + row2 = _mm_load_si128((const __m128i *) (data + 2*8)); + row3 = _mm_load_si128((const __m128i *) (data + 3*8)); + row4 = _mm_load_si128((const __m128i *) (data + 4*8)); + row5 = _mm_load_si128((const __m128i *) (data + 5*8)); + row6 = _mm_load_si128((const __m128i *) (data + 6*8)); + row7 = _mm_load_si128((const __m128i *) (data + 7*8)); + + // column pass + dct_pass(bias_0, 10); + + { + // 16bit 8x8 transpose pass 1 + dct_interleave16(row0, row4); + dct_interleave16(row1, row5); + dct_interleave16(row2, row6); + dct_interleave16(row3, row7); + + // transpose pass 2 + dct_interleave16(row0, row2); + dct_interleave16(row1, row3); + dct_interleave16(row4, row6); + dct_interleave16(row5, row7); + + // transpose pass 3 + dct_interleave16(row0, row1); + dct_interleave16(row2, row3); + dct_interleave16(row4, row5); + dct_interleave16(row6, row7); + } + + // row pass + dct_pass(bias_1, 17); + + { + // pack + __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 + __m128i p1 = _mm_packus_epi16(row2, row3); + __m128i p2 = _mm_packus_epi16(row4, row5); + __m128i p3 = _mm_packus_epi16(row6, row7); + + // 8bit 8x8 transpose pass 1 + dct_interleave8(p0, p2); // a0e0a1e1... + dct_interleave8(p1, p3); // c0g0c1g1... + + // transpose pass 2 + dct_interleave8(p0, p1); // a0c0e0g0... + dct_interleave8(p2, p3); // b0d0f0h0... + + // transpose pass 3 + dct_interleave8(p0, p2); // a0b0c0d0... + dct_interleave8(p1, p3); // a4b4c4d4... + + // store + _mm_storel_epi64((__m128i *) out, p0); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p2); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p1); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p3); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e)); + } + +#undef dct_const +#undef dct_rot +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_interleave8 +#undef dct_interleave16 +#undef dct_pass +} + +#endif // STBI_SSE2 + +#ifdef STBI_NEON + +// NEON integer IDCT. should produce bit-identical +// results to the generic C version. +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; + + int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); + int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); + int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f)); + int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f)); + int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); + int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); + int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); + int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); + int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f)); + int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f)); + int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f)); + int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f)); + +#define dct_long_mul(out, inq, coeff) \ + int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) + +#define dct_long_mac(out, acc, inq, coeff) \ + int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) + +#define dct_widen(out, inq) \ + int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ + int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) + +// wide add +#define dct_wadd(out, a, b) \ + int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vaddq_s32(a##_h, b##_h) + +// wide sub +#define dct_wsub(out, a, b) \ + int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vsubq_s32(a##_h, b##_h) + +// butterfly a/b, then shift using "shiftop" by "s" and pack +#define dct_bfly32o(out0,out1, a,b,shiftop,s) \ + { \ + dct_wadd(sum, a, b); \ + dct_wsub(dif, a, b); \ + out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ + out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ + } + +#define dct_pass(shiftop, shift) \ + { \ + /* even part */ \ + int16x8_t sum26 = vaddq_s16(row2, row6); \ + dct_long_mul(p1e, sum26, rot0_0); \ + dct_long_mac(t2e, p1e, row6, rot0_1); \ + dct_long_mac(t3e, p1e, row2, rot0_2); \ + int16x8_t sum04 = vaddq_s16(row0, row4); \ + int16x8_t dif04 = vsubq_s16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + int16x8_t sum15 = vaddq_s16(row1, row5); \ + int16x8_t sum17 = vaddq_s16(row1, row7); \ + int16x8_t sum35 = vaddq_s16(row3, row5); \ + int16x8_t sum37 = vaddq_s16(row3, row7); \ + int16x8_t sumodd = vaddq_s16(sum17, sum35); \ + dct_long_mul(p5o, sumodd, rot1_0); \ + dct_long_mac(p1o, p5o, sum17, rot1_1); \ + dct_long_mac(p2o, p5o, sum35, rot1_2); \ + dct_long_mul(p3o, sum37, rot2_0); \ + dct_long_mul(p4o, sum15, rot2_1); \ + dct_wadd(sump13o, p1o, p3o); \ + dct_wadd(sump24o, p2o, p4o); \ + dct_wadd(sump23o, p2o, p3o); \ + dct_wadd(sump14o, p1o, p4o); \ + dct_long_mac(x4, sump13o, row7, rot3_0); \ + dct_long_mac(x5, sump24o, row5, rot3_1); \ + dct_long_mac(x6, sump23o, row3, rot3_2); \ + dct_long_mac(x7, sump14o, row1, rot3_3); \ + dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \ + dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \ + dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \ + dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \ + } + + // load + row0 = vld1q_s16(data + 0*8); + row1 = vld1q_s16(data + 1*8); + row2 = vld1q_s16(data + 2*8); + row3 = vld1q_s16(data + 3*8); + row4 = vld1q_s16(data + 4*8); + row5 = vld1q_s16(data + 5*8); + row6 = vld1q_s16(data + 6*8); + row7 = vld1q_s16(data + 7*8); + + // add DC bias + row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); + + // column pass + dct_pass(vrshrn_n_s32, 10); + + // 16bit 8x8 transpose + { +// these three map to a single VTRN.16, VTRN.32, and VSWP, respectively. +// whether compilers actually get this is another story, sadly. +#define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); } +#define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); } + + // pass 1 + dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 + dct_trn16(row2, row3); + dct_trn16(row4, row5); + dct_trn16(row6, row7); + + // pass 2 + dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 + dct_trn32(row1, row3); + dct_trn32(row4, row6); + dct_trn32(row5, row7); + + // pass 3 + dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 + dct_trn64(row1, row5); + dct_trn64(row2, row6); + dct_trn64(row3, row7); + +#undef dct_trn16 +#undef dct_trn32 +#undef dct_trn64 + } + + // row pass + // vrshrn_n_s32 only supports shifts up to 16, we need + // 17. so do a non-rounding shift of 16 first then follow + // up with a rounding shift by 1. + dct_pass(vshrn_n_s32, 16); + + { + // pack and round + uint8x8_t p0 = vqrshrun_n_s16(row0, 1); + uint8x8_t p1 = vqrshrun_n_s16(row1, 1); + uint8x8_t p2 = vqrshrun_n_s16(row2, 1); + uint8x8_t p3 = vqrshrun_n_s16(row3, 1); + uint8x8_t p4 = vqrshrun_n_s16(row4, 1); + uint8x8_t p5 = vqrshrun_n_s16(row5, 1); + uint8x8_t p6 = vqrshrun_n_s16(row6, 1); + uint8x8_t p7 = vqrshrun_n_s16(row7, 1); + + // again, these can translate into one instruction, but often don't. +#define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); } +#define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); } + + // sadly can't use interleaved stores here since we only write + // 8 bytes to each scan line! + + // 8x8 8-bit transpose pass 1 + dct_trn8_8(p0, p1); + dct_trn8_8(p2, p3); + dct_trn8_8(p4, p5); + dct_trn8_8(p6, p7); + + // pass 2 + dct_trn8_16(p0, p2); + dct_trn8_16(p1, p3); + dct_trn8_16(p4, p6); + dct_trn8_16(p5, p7); + + // pass 3 + dct_trn8_32(p0, p4); + dct_trn8_32(p1, p5); + dct_trn8_32(p2, p6); + dct_trn8_32(p3, p7); + + // store + vst1_u8(out, p0); out += out_stride; + vst1_u8(out, p1); out += out_stride; + vst1_u8(out, p2); out += out_stride; + vst1_u8(out, p3); out += out_stride; + vst1_u8(out, p4); out += out_stride; + vst1_u8(out, p5); out += out_stride; + vst1_u8(out, p6); out += out_stride; + vst1_u8(out, p7); + +#undef dct_trn8_8 +#undef dct_trn8_16 +#undef dct_trn8_32 + } + +#undef dct_long_mul +#undef dct_long_mac +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_pass +} + +#endif // STBI_NEON + +#define STBI__MARKER_none 0xff +// if there's a pending marker from the entropy stream, return that +// otherwise, fetch from the stream and get a marker. if there's no +// marker, return 0xff, which is never a valid marker value +static stbi_uc stbi__get_marker(stbi__jpeg *j) +{ + stbi_uc x; + if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } + x = stbi__get8(j->s); + if (x != 0xff) return STBI__MARKER_none; + while (x == 0xff) + x = stbi__get8(j->s); // consume repeated 0xff fill bytes + return x; +} + +// in each scan, we'll have scan_n components, and the order +// of the components is specified by order[] +#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) + +// after a restart interval, stbi__jpeg_reset the entropy decoder and +// the dc prediction +static void stbi__jpeg_reset(stbi__jpeg *j) +{ + j->code_bits = 0; + j->code_buffer = 0; + j->nomore = 0; + j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0; + j->marker = STBI__MARKER_none; + j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; + j->eob_run = 0; + // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, + // since we don't even allow 1<<30 pixels +} + +static int stbi__parse_entropy_coded_data(stbi__jpeg *z) +{ + stbi__jpeg_reset(z); + if (!z->progressive) { + if (z->scan_n == 1) { + int i,j; + STBI_SIMD_ALIGN(short, data[64]); + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + // if it's NOT a restart, then just bail, so we get corrupt data + // rather than no data + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } else { // interleaved + int i,j,k,x,y; + STBI_SIMD_ALIGN(short, data[64]); + for (j=0; j < z->img_mcu_y; ++j) { + for (i=0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k=0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y=0; y < z->img_comp[n].v; ++y) { + for (x=0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x)*8; + int y2 = (j*z->img_comp[n].v + y)*8; + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data); + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } else { + if (z->scan_n == 1) { + int i,j; + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + if (z->spec_start == 0) { + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } else { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) + return 0; + } + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } else { // interleaved + int i,j,k,x,y; + for (j=0; j < z->img_mcu_y; ++j) { + for (i=0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k=0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y=0; y < z->img_comp[n].v; ++y) { + for (x=0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x); + int y2 = (j*z->img_comp[n].v + y); + short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } +} + +static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant) +{ + int i; + for (i=0; i < 64; ++i) + data[i] *= dequant[i]; +} + +static void stbi__jpeg_finish(stbi__jpeg *z) +{ + if (z->progressive) { + // dequantize and idct the data + int i,j,n; + for (n=0; n < z->s->img_n; ++n) { + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); + } + } + } + } +} + +static int stbi__process_marker(stbi__jpeg *z, int m) +{ + int L; + switch (m) { + case STBI__MARKER_none: // no marker found + return stbi__err("expected marker","Corrupt JPEG"); + + case 0xDD: // DRI - specify restart interval + if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG"); + z->restart_interval = stbi__get16be(z->s); + return 1; + + case 0xDB: // DQT - define quantization table + L = stbi__get16be(z->s)-2; + while (L > 0) { + int q = stbi__get8(z->s); + int p = q >> 4, sixteen = (p != 0); + int t = q & 15,i; + if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG"); + if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG"); + + for (i=0; i < 64; ++i) + z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s)); + L -= (sixteen ? 129 : 65); + } + return L==0; + + case 0xC4: // DHT - define huffman table + L = stbi__get16be(z->s)-2; + while (L > 0) { + stbi_uc *v; + int sizes[16],i,n=0; + int q = stbi__get8(z->s); + int tc = q >> 4; + int th = q & 15; + if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG"); + for (i=0; i < 16; ++i) { + sizes[i] = stbi__get8(z->s); + n += sizes[i]; + } + L -= 17; + if (tc == 0) { + if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0; + v = z->huff_dc[th].values; + } else { + if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0; + v = z->huff_ac[th].values; + } + for (i=0; i < n; ++i) + v[i] = stbi__get8(z->s); + if (tc != 0) + stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); + L -= n; + } + return L==0; + } + + // check for comment block or APP blocks + if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { + L = stbi__get16be(z->s); + if (L < 2) { + if (m == 0xFE) + return stbi__err("bad COM len","Corrupt JPEG"); + else + return stbi__err("bad APP len","Corrupt JPEG"); + } + L -= 2; + + if (m == 0xE0 && L >= 5) { // JFIF APP0 segment + static const unsigned char tag[5] = {'J','F','I','F','\0'}; + int ok = 1; + int i; + for (i=0; i < 5; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 5; + if (ok) + z->jfif = 1; + } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment + static const unsigned char tag[6] = {'A','d','o','b','e','\0'}; + int ok = 1; + int i; + for (i=0; i < 6; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 6; + if (ok) { + stbi__get8(z->s); // version + stbi__get16be(z->s); // flags0 + stbi__get16be(z->s); // flags1 + z->app14_color_transform = stbi__get8(z->s); // color transform + L -= 6; + } + } + + stbi__skip(z->s, L); + return 1; + } + + return stbi__err("unknown marker","Corrupt JPEG"); +} + +// after we see SOS +static int stbi__process_scan_header(stbi__jpeg *z) +{ + int i; + int Ls = stbi__get16be(z->s); + z->scan_n = stbi__get8(z->s); + if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG"); + if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG"); + for (i=0; i < z->scan_n; ++i) { + int id = stbi__get8(z->s), which; + int q = stbi__get8(z->s); + for (which = 0; which < z->s->img_n; ++which) + if (z->img_comp[which].id == id) + break; + if (which == z->s->img_n) return 0; // no match + z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG"); + z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG"); + z->order[i] = which; + } + + { + int aa; + z->spec_start = stbi__get8(z->s); + z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 + aa = stbi__get8(z->s); + z->succ_high = (aa >> 4); + z->succ_low = (aa & 15); + if (z->progressive) { + if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13) + return stbi__err("bad SOS", "Corrupt JPEG"); + } else { + if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG"); + if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG"); + z->spec_end = 63; + } + } + + return 1; +} + +static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why) +{ + int i; + for (i=0; i < ncomp; ++i) { + if (z->img_comp[i].raw_data) { + STBI_FREE(z->img_comp[i].raw_data); + z->img_comp[i].raw_data = NULL; + z->img_comp[i].data = NULL; + } + if (z->img_comp[i].raw_coeff) { + STBI_FREE(z->img_comp[i].raw_coeff); + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].coeff = 0; + } + if (z->img_comp[i].linebuf) { + STBI_FREE(z->img_comp[i].linebuf); + z->img_comp[i].linebuf = NULL; + } + } + return why; +} + +static int stbi__process_frame_header(stbi__jpeg *z, int scan) +{ + stbi__context *s = z->s; + int Lf,p,i,q, h_max=1,v_max=1,c; + Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG + p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline + s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG + s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires + c = stbi__get8(s); + if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG"); + s->img_n = c; + for (i=0; i < c; ++i) { + z->img_comp[i].data = NULL; + z->img_comp[i].linebuf = NULL; + } + + if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG"); + + z->rgb = 0; + for (i=0; i < s->img_n; ++i) { + static const unsigned char rgb[3] = { 'R', 'G', 'B' }; + z->img_comp[i].id = stbi__get8(s); + if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) + ++z->rgb; + q = stbi__get8(s); + z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG"); + z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG"); + z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG"); + } + + if (scan != STBI__SCAN_load) return 1; + + if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode"); + + for (i=0; i < s->img_n; ++i) { + if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; + if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; + } + + // compute interleaved mcu info + z->img_h_max = h_max; + z->img_v_max = v_max; + z->img_mcu_w = h_max * 8; + z->img_mcu_h = v_max * 8; + // these sizes can't be more than 17 bits + z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; + z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; + + for (i=0; i < s->img_n; ++i) { + // number of effective pixels (e.g. for non-interleaved MCU) + z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max; + z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max; + // to simplify generation, we'll allocate enough memory to decode + // the bogus oversized data from using interleaved MCUs and their + // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't + // discard the extra data until colorspace conversion + // + // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier) + // so these muls can't overflow with 32-bit ints (which we require) + z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; + z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; + z->img_comp[i].coeff = 0; + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].linebuf = NULL; + z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); + if (z->img_comp[i].raw_data == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); + // align blocks for idct using mmx/sse + z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); + if (z->progressive) { + // w2, h2 are multiples of 8 (see above) + z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; + z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; + z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); + if (z->img_comp[i].raw_coeff == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); + z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); + } + } + + return 1; +} + +// use comparisons since in some cases we handle more than one case (e.g. SOF) +#define stbi__DNL(x) ((x) == 0xdc) +#define stbi__SOI(x) ((x) == 0xd8) +#define stbi__EOI(x) ((x) == 0xd9) +#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) +#define stbi__SOS(x) ((x) == 0xda) + +#define stbi__SOF_progressive(x) ((x) == 0xc2) + +static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) +{ + int m; + z->jfif = 0; + z->app14_color_transform = -1; // valid values are 0,1,2 + z->marker = STBI__MARKER_none; // initialize cached marker to empty + m = stbi__get_marker(z); + if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG"); + if (scan == STBI__SCAN_type) return 1; + m = stbi__get_marker(z); + while (!stbi__SOF(m)) { + if (!stbi__process_marker(z,m)) return 0; + m = stbi__get_marker(z); + while (m == STBI__MARKER_none) { + // some files have extra padding after their blocks, so ok, we'll scan + if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); + m = stbi__get_marker(z); + } + } + z->progressive = stbi__SOF_progressive(m); + if (!stbi__process_frame_header(z, scan)) return 0; + return 1; +} + +// decode image to YCbCr format +static int stbi__decode_jpeg_image(stbi__jpeg *j) +{ + int m; + for (m = 0; m < 4; m++) { + j->img_comp[m].raw_data = NULL; + j->img_comp[m].raw_coeff = NULL; + } + j->restart_interval = 0; + if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; + m = stbi__get_marker(j); + while (!stbi__EOI(m)) { + if (stbi__SOS(m)) { + if (!stbi__process_scan_header(j)) return 0; + if (!stbi__parse_entropy_coded_data(j)) return 0; + if (j->marker == STBI__MARKER_none ) { + // handle 0s at the end of image data from IP Kamera 9060 + while (!stbi__at_eof(j->s)) { + int x = stbi__get8(j->s); + if (x == 255) { + j->marker = stbi__get8(j->s); + break; + } + } + // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 + } + } else if (stbi__DNL(m)) { + int Ld = stbi__get16be(j->s); + stbi__uint32 NL = stbi__get16be(j->s); + if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); + if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); + } else { + if (!stbi__process_marker(j, m)) return 0; + } + m = stbi__get_marker(j); + } + if (j->progressive) + stbi__jpeg_finish(j); + return 1; +} + +// static jfif-centered resampling (across block boundaries) + +typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1, + int w, int hs); + +#define stbi__div4(x) ((stbi_uc) ((x) >> 2)) + +static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + STBI_NOTUSED(out); + STBI_NOTUSED(in_far); + STBI_NOTUSED(w); + STBI_NOTUSED(hs); + return in_near; +} + +static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples vertically for every one in input + int i; + STBI_NOTUSED(hs); + for (i=0; i < w; ++i) + out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2); + return out; +} + +static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples horizontally for every one in input + int i; + stbi_uc *input = in_near; + + if (w == 1) { + // if only one sample, can't do any interpolation + out[0] = out[1] = input[0]; + return out; + } + + out[0] = input[0]; + out[1] = stbi__div4(input[0]*3 + input[1] + 2); + for (i=1; i < w-1; ++i) { + int n = 3*input[i]+2; + out[i*2+0] = stbi__div4(n+input[i-1]); + out[i*2+1] = stbi__div4(n+input[i+1]); + } + out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2); + out[i*2+1] = input[w-1]; + + STBI_NOTUSED(in_far); + STBI_NOTUSED(hs); + + return out; +} + +#define stbi__div16(x) ((stbi_uc) ((x) >> 4)) + +static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i,t0,t1; + if (w == 1) { + out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3*in_near[0] + in_far[0]; + out[0] = stbi__div4(t1+2); + for (i=1; i < w; ++i) { + t0 = t1; + t1 = 3*in_near[i]+in_far[i]; + out[i*2-1] = stbi__div16(3*t0 + t1 + 8); + out[i*2 ] = stbi__div16(3*t1 + t0 + 8); + } + out[w*2-1] = stbi__div4(t1+2); + + STBI_NOTUSED(hs); + + return out; +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i=0,t0,t1; + + if (w == 1) { + out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3*in_near[0] + in_far[0]; + // process groups of 8 pixels for as long as we can. + // note we can't handle the last pixel in a row in this loop + // because we need to handle the filter boundary conditions. + for (; i < ((w-1) & ~7); i += 8) { +#if defined(STBI_SSE2) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + __m128i zero = _mm_setzero_si128(); + __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i)); + __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i)); + __m128i farw = _mm_unpacklo_epi8(farb, zero); + __m128i nearw = _mm_unpacklo_epi8(nearb, zero); + __m128i diff = _mm_sub_epi16(farw, nearw); + __m128i nears = _mm_slli_epi16(nearw, 2); + __m128i curr = _mm_add_epi16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + __m128i prv0 = _mm_slli_si128(curr, 2); + __m128i nxt0 = _mm_srli_si128(curr, 2); + __m128i prev = _mm_insert_epi16(prv0, t1, 0); + __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + __m128i bias = _mm_set1_epi16(8); + __m128i curs = _mm_slli_epi16(curr, 2); + __m128i prvd = _mm_sub_epi16(prev, curr); + __m128i nxtd = _mm_sub_epi16(next, curr); + __m128i curb = _mm_add_epi16(curs, bias); + __m128i even = _mm_add_epi16(prvd, curb); + __m128i odd = _mm_add_epi16(nxtd, curb); + + // interleave even and odd pixels, then undo scaling. + __m128i int0 = _mm_unpacklo_epi16(even, odd); + __m128i int1 = _mm_unpackhi_epi16(even, odd); + __m128i de0 = _mm_srli_epi16(int0, 4); + __m128i de1 = _mm_srli_epi16(int1, 4); + + // pack and write output + __m128i outv = _mm_packus_epi16(de0, de1); + _mm_storeu_si128((__m128i *) (out + i*2), outv); +#elif defined(STBI_NEON) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + uint8x8_t farb = vld1_u8(in_far + i); + uint8x8_t nearb = vld1_u8(in_near + i); + int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); + int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); + int16x8_t curr = vaddq_s16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + int16x8_t prv0 = vextq_s16(curr, curr, 7); + int16x8_t nxt0 = vextq_s16(curr, curr, 1); + int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); + int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + int16x8_t curs = vshlq_n_s16(curr, 2); + int16x8_t prvd = vsubq_s16(prev, curr); + int16x8_t nxtd = vsubq_s16(next, curr); + int16x8_t even = vaddq_s16(curs, prvd); + int16x8_t odd = vaddq_s16(curs, nxtd); + + // undo scaling and round, then store with even/odd phases interleaved + uint8x8x2_t o; + o.val[0] = vqrshrun_n_s16(even, 4); + o.val[1] = vqrshrun_n_s16(odd, 4); + vst2_u8(out + i*2, o); +#endif + + // "previous" value for next iter + t1 = 3*in_near[i+7] + in_far[i+7]; + } + + t0 = t1; + t1 = 3*in_near[i] + in_far[i]; + out[i*2] = stbi__div16(3*t1 + t0 + 8); + + for (++i; i < w; ++i) { + t0 = t1; + t1 = 3*in_near[i]+in_far[i]; + out[i*2-1] = stbi__div16(3*t0 + t1 + 8); + out[i*2 ] = stbi__div16(3*t1 + t0 + 8); + } + out[w*2-1] = stbi__div4(t1+2); + + STBI_NOTUSED(hs); + + return out; +} +#endif + +static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // resample with nearest-neighbor + int i,j; + STBI_NOTUSED(in_far); + for (i=0; i < w; ++i) + for (j=0; j < hs; ++j) + out[i*hs+j] = in_near[i]; + return out; +} + +// this is a reduced-precision calculation of YCbCr-to-RGB introduced +// to make sure the code produces the same results in both SIMD and scalar +#define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) +static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) +{ + int i; + for (i=0; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1<<19); // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) +{ + int i = 0; + +#ifdef STBI_SSE2 + // step == 3 is pretty ugly on the final interleave, and i'm not convinced + // it's useful in practice (you wouldn't use it for textures, for example). + // so just accelerate step == 4 case. + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + __m128i signflip = _mm_set1_epi8(-0x80); + __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f)); + __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f)); + __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f)); + __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f)); + __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128); + __m128i xw = _mm_set1_epi16(255); // alpha channel + + for (; i+7 < count; i += 8) { + // load + __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i)); + __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i)); + __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i)); + __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 + __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 + + // unpack to short (and left-shift cr, cb by 8) + __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); + __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); + __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); + + // color transform + __m128i yws = _mm_srli_epi16(yw, 4); + __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); + __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); + __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); + __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); + __m128i rws = _mm_add_epi16(cr0, yws); + __m128i gwt = _mm_add_epi16(cb0, yws); + __m128i bws = _mm_add_epi16(yws, cb1); + __m128i gws = _mm_add_epi16(gwt, cr1); + + // descale + __m128i rw = _mm_srai_epi16(rws, 4); + __m128i bw = _mm_srai_epi16(bws, 4); + __m128i gw = _mm_srai_epi16(gws, 4); + + // back to byte, set up for transpose + __m128i brb = _mm_packus_epi16(rw, bw); + __m128i gxb = _mm_packus_epi16(gw, xw); + + // transpose to interleave channels + __m128i t0 = _mm_unpacklo_epi8(brb, gxb); + __m128i t1 = _mm_unpackhi_epi8(brb, gxb); + __m128i o0 = _mm_unpacklo_epi16(t0, t1); + __m128i o1 = _mm_unpackhi_epi16(t0, t1); + + // store + _mm_storeu_si128((__m128i *) (out + 0), o0); + _mm_storeu_si128((__m128i *) (out + 16), o1); + out += 32; + } + } +#endif + +#ifdef STBI_NEON + // in this version, step=3 support would be easy to add. but is there demand? + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + uint8x8_t signflip = vdup_n_u8(0x80); + int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f)); + int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f)); + int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f)); + int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f)); + + for (; i+7 < count; i += 8) { + // load + uint8x8_t y_bytes = vld1_u8(y + i); + uint8x8_t cr_bytes = vld1_u8(pcr + i); + uint8x8_t cb_bytes = vld1_u8(pcb + i); + int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); + int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); + + // expand to s16 + int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); + int16x8_t crw = vshll_n_s8(cr_biased, 7); + int16x8_t cbw = vshll_n_s8(cb_biased, 7); + + // color transform + int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); + int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); + int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); + int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); + int16x8_t rws = vaddq_s16(yws, cr0); + int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); + int16x8_t bws = vaddq_s16(yws, cb1); + + // undo scaling, round, convert to byte + uint8x8x4_t o; + o.val[0] = vqrshrun_n_s16(rws, 4); + o.val[1] = vqrshrun_n_s16(gws, 4); + o.val[2] = vqrshrun_n_s16(bws, 4); + o.val[3] = vdup_n_u8(255); + + // store, interleaving r/g/b/a + vst4_u8(out, o); + out += 8*4; + } + } +#endif + + for (; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1<<19); // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} +#endif + +// set up the kernels +static void stbi__setup_jpeg(stbi__jpeg *j) +{ + j->idct_block_kernel = stbi__idct_block; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; + +#ifdef STBI_SSE2 + if (stbi__sse2_available()) { + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; + } +#endif + +#ifdef STBI_NEON + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; +#endif +} + +// clean up the temporary component buffers +static void stbi__cleanup_jpeg(stbi__jpeg *j) +{ + stbi__free_jpeg_components(j, j->s->img_n, 0); +} + +typedef struct +{ + resample_row_func resample; + stbi_uc *line0,*line1; + int hs,vs; // expansion factor in each axis + int w_lores; // horizontal pixels pre-expansion + int ystep; // how far through vertical expansion we are + int ypos; // which pre-expansion row we're on +} stbi__resample; + +// fast 0..255 * 0..255 => 0..255 rounded multiplication +static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) +{ + unsigned int t = x*y + 128; + return (stbi_uc) ((t + (t >>8)) >> 8); +} + +static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) +{ + int n, decode_n, is_rgb; + z->s->img_n = 0; // make stbi__cleanup_jpeg safe + + // validate req_comp + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + + // load a jpeg image from whichever source, but leave in YCbCr format + if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } + + // determine actual number of components to generate + n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; + + is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); + + if (z->s->img_n == 3 && n < 3 && !is_rgb) + decode_n = 1; + else + decode_n = z->s->img_n; + + // resample and color-convert + { + int k; + unsigned int i,j; + stbi_uc *output; + stbi_uc *coutput[4]; + + stbi__resample res_comp[4]; + + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + + // allocate line buffer big enough for upsampling off the edges + // with upsample factor of 4 + z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3); + if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + r->hs = z->img_h_max / z->img_comp[k].h; + r->vs = z->img_v_max / z->img_comp[k].v; + r->ystep = r->vs >> 1; + r->w_lores = (z->s->img_x + r->hs-1) / r->hs; + r->ypos = 0; + r->line0 = r->line1 = z->img_comp[k].data; + + if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; + else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; + else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; + else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; + else r->resample = stbi__resample_row_generic; + } + + // can't error after this so, this is safe + output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); + if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + // now go ahead and resample + for (j=0; j < z->s->img_y; ++j) { + stbi_uc *out = output + n * z->s->img_x * j; + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + int y_bot = r->ystep >= (r->vs >> 1); + coutput[k] = r->resample(z->img_comp[k].linebuf, + y_bot ? r->line1 : r->line0, + y_bot ? r->line0 : r->line1, + r->w_lores, r->hs); + if (++r->ystep >= r->vs) { + r->ystep = 0; + r->line0 = r->line1; + if (++r->ypos < z->img_comp[k].y) + r->line1 += z->img_comp[k].w2; + } + } + if (n >= 3) { + stbi_uc *y = coutput[0]; + if (z->s->img_n == 3) { + if (is_rgb) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = y[i]; + out[1] = coutput[1][i]; + out[2] = coutput[2][i]; + out[3] = 255; + out += n; + } + } else { + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } else if (z->s->img_n == 4) { + if (z->app14_color_transform == 0) { // CMYK + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(coutput[0][i], m); + out[1] = stbi__blinn_8x8(coutput[1][i], m); + out[2] = stbi__blinn_8x8(coutput[2][i], m); + out[3] = 255; + out += n; + } + } else if (z->app14_color_transform == 2) { // YCCK + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(255 - out[0], m); + out[1] = stbi__blinn_8x8(255 - out[1], m); + out[2] = stbi__blinn_8x8(255 - out[2], m); + out += n; + } + } else { // YCbCr + alpha? Ignore the fourth channel for now + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } else + for (i=0; i < z->s->img_x; ++i) { + out[0] = out[1] = out[2] = y[i]; + out[3] = 255; // not used if n==3 + out += n; + } + } else { + if (is_rgb) { + if (n == 1) + for (i=0; i < z->s->img_x; ++i) + *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + else { + for (i=0; i < z->s->img_x; ++i, out += 2) { + out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + out[1] = 255; + } + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 0) { + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); + stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); + stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); + out[0] = stbi__compute_y(r, g, b); + out[1] = 255; + out += n; + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 2) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); + out[1] = 255; + out += n; + } + } else { + stbi_uc *y = coutput[0]; + if (n == 1) + for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; + else + for (i=0; i < z->s->img_x; ++i) *out++ = y[i], *out++ = 255; + } + } + } + stbi__cleanup_jpeg(z); + *out_x = z->s->img_x; + *out_y = z->s->img_y; + if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output + return output; + } +} + +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + unsigned char* result; + stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg)); + STBI_NOTUSED(ri); + j->s = s; + stbi__setup_jpeg(j); + result = load_jpeg_image(j, x,y,comp,req_comp); + STBI_FREE(j); + return result; +} + +static int stbi__jpeg_test(stbi__context *s) +{ + int r; + stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); + j->s = s; + stbi__setup_jpeg(j); + r = stbi__decode_jpeg_header(j, STBI__SCAN_type); + stbi__rewind(s); + STBI_FREE(j); + return r; +} + +static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) +{ + if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { + stbi__rewind( j->s ); + return 0; + } + if (x) *x = j->s->img_x; + if (y) *y = j->s->img_y; + if (comp) *comp = j->s->img_n >= 3 ? 3 : 1; + return 1; +} + +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) +{ + int result; + stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg))); + j->s = s; + result = stbi__jpeg_info_raw(j, x, y, comp); + STBI_FREE(j); + return result; +} +#endif + +// public domain zlib decode v0.2 Sean Barrett 2006-11-18 +// simple implementation +// - all input must be provided in an upfront buffer +// - all output is written to a single output buffer (can malloc/realloc) +// performance +// - fast huffman + +#ifndef STBI_NO_ZLIB + +// fast-way is faster to check than jpeg huffman, but slow way is slower +#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables +#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) + +// zlib-style huffman encoding +// (jpegs packs from left, zlib from right, so can't share code) +typedef struct +{ + stbi__uint16 fast[1 << STBI__ZFAST_BITS]; + stbi__uint16 firstcode[16]; + int maxcode[17]; + stbi__uint16 firstsymbol[16]; + stbi_uc size[288]; + stbi__uint16 value[288]; +} stbi__zhuffman; + +stbi_inline static int stbi__bitreverse16(int n) +{ + n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); + n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); + n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); + n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); + return n; +} + +stbi_inline static int stbi__bit_reverse(int v, int bits) +{ + STBI_ASSERT(bits <= 16); + // to bit reverse n bits, reverse 16 and shift + // e.g. 11 bits, bit reverse and shift away 5 + return stbi__bitreverse16(v) >> (16-bits); +} + +static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num) +{ + int i,k=0; + int code, next_code[16], sizes[17]; + + // DEFLATE spec for generating codes + memset(sizes, 0, sizeof(sizes)); + memset(z->fast, 0, sizeof(z->fast)); + for (i=0; i < num; ++i) + ++sizes[sizelist[i]]; + sizes[0] = 0; + for (i=1; i < 16; ++i) + if (sizes[i] > (1 << i)) + return stbi__err("bad sizes", "Corrupt PNG"); + code = 0; + for (i=1; i < 16; ++i) { + next_code[i] = code; + z->firstcode[i] = (stbi__uint16) code; + z->firstsymbol[i] = (stbi__uint16) k; + code = (code + sizes[i]); + if (sizes[i]) + if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG"); + z->maxcode[i] = code << (16-i); // preshift for inner loop + code <<= 1; + k += sizes[i]; + } + z->maxcode[16] = 0x10000; // sentinel + for (i=0; i < num; ++i) { + int s = sizelist[i]; + if (s) { + int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; + stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i); + z->size [c] = (stbi_uc ) s; + z->value[c] = (stbi__uint16) i; + if (s <= STBI__ZFAST_BITS) { + int j = stbi__bit_reverse(next_code[s],s); + while (j < (1 << STBI__ZFAST_BITS)) { + z->fast[j] = fastv; + j += (1 << s); + } + } + ++next_code[s]; + } + } + return 1; +} + +// zlib-from-memory implementation for PNG reading +// because PNG allows splitting the zlib stream arbitrarily, +// and it's annoying structurally to have PNG call ZLIB call PNG, +// we require PNG read all the IDATs and combine them into a single +// memory buffer + +typedef struct +{ + stbi_uc *zbuffer, *zbuffer_end; + int num_bits; + stbi__uint32 code_buffer; + + char *zout; + char *zout_start; + char *zout_end; + int z_expandable; + + stbi__zhuffman z_length, z_distance; +} stbi__zbuf; + +stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) +{ + if (z->zbuffer >= z->zbuffer_end) return 0; + return *z->zbuffer++; +} + +static void stbi__fill_bits(stbi__zbuf *z) +{ + do { + STBI_ASSERT(z->code_buffer < (1U << z->num_bits)); + z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits; + z->num_bits += 8; + } while (z->num_bits <= 24); +} + +stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n) +{ + unsigned int k; + if (z->num_bits < n) stbi__fill_bits(z); + k = z->code_buffer & ((1 << n) - 1); + z->code_buffer >>= n; + z->num_bits -= n; + return k; +} + +static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b,s,k; + // not resolved by fast table, so compute it the slow way + // use jpeg approach, which requires MSbits at top + k = stbi__bit_reverse(a->code_buffer, 16); + for (s=STBI__ZFAST_BITS+1; ; ++s) + if (k < z->maxcode[s]) + break; + if (s == 16) return -1; // invalid code! + // code size is s, so: + b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; + STBI_ASSERT(z->size[b] == s); + a->code_buffer >>= s; + a->num_bits -= s; + return z->value[b]; +} + +stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b,s; + if (a->num_bits < 16) stbi__fill_bits(a); + b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; + if (b) { + s = b >> 9; + a->code_buffer >>= s; + a->num_bits -= s; + return b & 511; + } + return stbi__zhuffman_decode_slowpath(a, z); +} + +static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes +{ + char *q; + int cur, limit, old_limit; + z->zout = zout; + if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); + cur = (int) (z->zout - z->zout_start); + limit = old_limit = (int) (z->zout_end - z->zout_start); + while (cur + n > limit) + limit *= 2; + q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); + STBI_NOTUSED(old_limit); + if (q == NULL) return stbi__err("outofmem", "Out of memory"); + z->zout_start = q; + z->zout = q + cur; + z->zout_end = q + limit; + return 1; +} + +static const int stbi__zlength_base[31] = { + 3,4,5,6,7,8,9,10,11,13, + 15,17,19,23,27,31,35,43,51,59, + 67,83,99,115,131,163,195,227,258,0,0 }; + +static const int stbi__zlength_extra[31]= +{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; + +static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, +257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; + +static const int stbi__zdist_extra[32] = +{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +static int stbi__parse_huffman_block(stbi__zbuf *a) +{ + char *zout = a->zout; + for(;;) { + int z = stbi__zhuffman_decode(a, &a->z_length); + if (z < 256) { + if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes + if (zout >= a->zout_end) { + if (!stbi__zexpand(a, zout, 1)) return 0; + zout = a->zout; + } + *zout++ = (char) z; + } else { + stbi_uc *p; + int len,dist; + if (z == 256) { + a->zout = zout; + return 1; + } + z -= 257; + len = stbi__zlength_base[z]; + if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); + z = stbi__zhuffman_decode(a, &a->z_distance); + if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); + dist = stbi__zdist_base[z]; + if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); + if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG"); + if (zout + len > a->zout_end) { + if (!stbi__zexpand(a, zout, len)) return 0; + zout = a->zout; + } + p = (stbi_uc *) (zout - dist); + if (dist == 1) { // run of one byte; common in images. + stbi_uc v = *p; + if (len) { do *zout++ = v; while (--len); } + } else { + if (len) { do *zout++ = *p++; while (--len); } + } + } + } +} + +static int stbi__compute_huffman_codes(stbi__zbuf *a) +{ + static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; + stbi__zhuffman z_codelength; + stbi_uc lencodes[286+32+137];//padding for maximum single op + stbi_uc codelength_sizes[19]; + int i,n; + + int hlit = stbi__zreceive(a,5) + 257; + int hdist = stbi__zreceive(a,5) + 1; + int hclen = stbi__zreceive(a,4) + 4; + int ntot = hlit + hdist; + + memset(codelength_sizes, 0, sizeof(codelength_sizes)); + for (i=0; i < hclen; ++i) { + int s = stbi__zreceive(a,3); + codelength_sizes[length_dezigzag[i]] = (stbi_uc) s; + } + if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; + + n = 0; + while (n < ntot) { + int c = stbi__zhuffman_decode(a, &z_codelength); + if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); + if (c < 16) + lencodes[n++] = (stbi_uc) c; + else { + stbi_uc fill = 0; + if (c == 16) { + c = stbi__zreceive(a,2)+3; + if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); + fill = lencodes[n-1]; + } else if (c == 17) + c = stbi__zreceive(a,3)+3; + else { + STBI_ASSERT(c == 18); + c = stbi__zreceive(a,7)+11; + } + if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); + memset(lencodes+n, fill, c); + n += c; + } + } + if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG"); + if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; + return 1; +} + +static int stbi__parse_uncompressed_block(stbi__zbuf *a) +{ + stbi_uc header[4]; + int len,nlen,k; + if (a->num_bits & 7) + stbi__zreceive(a, a->num_bits & 7); // discard + // drain the bit-packed data into header + k = 0; + while (a->num_bits > 0) { + header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check + a->code_buffer >>= 8; + a->num_bits -= 8; + } + STBI_ASSERT(a->num_bits == 0); + // now fill header the normal way + while (k < 4) + header[k++] = stbi__zget8(a); + len = header[1] * 256 + header[0]; + nlen = header[3] * 256 + header[2]; + if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG"); + if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG"); + if (a->zout + len > a->zout_end) + if (!stbi__zexpand(a, a->zout, len)) return 0; + memcpy(a->zout, a->zbuffer, len); + a->zbuffer += len; + a->zout += len; + return 1; +} + +static int stbi__parse_zlib_header(stbi__zbuf *a) +{ + int cmf = stbi__zget8(a); + int cm = cmf & 15; + /* int cinfo = cmf >> 4; */ + int flg = stbi__zget8(a); + if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec + if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png + if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png + // window = 1 << (8 + cinfo)... but who cares, we fully buffer output + return 1; +} + +static const stbi_uc stbi__zdefault_length[288] = +{ + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8 +}; +static const stbi_uc stbi__zdefault_distance[32] = +{ + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 +}; +/* +Init algorithm: +{ + int i; // use <= to match clearly with spec + for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; + for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9; + for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7; + for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8; + + for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; +} +*/ + +static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) +{ + int final, type; + if (parse_header) + if (!stbi__parse_zlib_header(a)) return 0; + a->num_bits = 0; + a->code_buffer = 0; + do { + final = stbi__zreceive(a,1); + type = stbi__zreceive(a,2); + if (type == 0) { + if (!stbi__parse_uncompressed_block(a)) return 0; + } else if (type == 3) { + return 0; + } else { + if (type == 1) { + // use fixed code lengths + if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , 288)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; + } else { + if (!stbi__compute_huffman_codes(a)) return 0; + } + if (!stbi__parse_huffman_block(a)) return 0; + } + } while (!final); + return 1; +} + +static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header) +{ + a->zout_start = obuf; + a->zout = obuf; + a->zout_end = obuf + olen; + a->z_expandable = exp; + + return stbi__parse_zlib(a, parse_header); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) +{ + return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) + return (int) (a.zout - a.zout_start); + else + return -1; +} + +STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(16384); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer+len; + if (stbi__do_zlib(&a, p, 16384, 1, 0)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) + return (int) (a.zout - a.zout_start); + else + return -1; +} +#endif + +// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 +// simple implementation +// - only 8-bit samples +// - no CRC checking +// - allocates lots of intermediate memory +// - avoids problem of streaming data between subsystems +// - avoids explicit window management +// performance +// - uses stb_zlib, a PD zlib implementation with fast huffman decoding + +#ifndef STBI_NO_PNG +typedef struct +{ + stbi__uint32 length; + stbi__uint32 type; +} stbi__pngchunk; + +static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) +{ + stbi__pngchunk c; + c.length = stbi__get32be(s); + c.type = stbi__get32be(s); + return c; +} + +static int stbi__check_png_header(stbi__context *s) +{ + static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; + int i; + for (i=0; i < 8; ++i) + if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG"); + return 1; +} + +typedef struct +{ + stbi__context *s; + stbi_uc *idata, *expanded, *out; + int depth; +} stbi__png; + + +enum { + STBI__F_none=0, + STBI__F_sub=1, + STBI__F_up=2, + STBI__F_avg=3, + STBI__F_paeth=4, + // synthetic filters used for first scanline to avoid needing a dummy row of 0s + STBI__F_avg_first, + STBI__F_paeth_first +}; + +static stbi_uc first_row_filter[5] = +{ + STBI__F_none, + STBI__F_sub, + STBI__F_none, + STBI__F_avg_first, + STBI__F_paeth_first +}; + +static int stbi__paeth(int a, int b, int c) +{ + int p = a + b - c; + int pa = abs(p-a); + int pb = abs(p-b); + int pc = abs(p-c); + if (pa <= pb && pa <= pc) return a; + if (pb <= pc) return b; + return c; +} + +static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; + +// create the png data from post-deflated data +static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) +{ + int bytes = (depth == 16? 2 : 1); + stbi__context *s = a->s; + stbi__uint32 i,j,stride = x*out_n*bytes; + stbi__uint32 img_len, img_width_bytes; + int k; + int img_n = s->img_n; // copy it into a local for later + + int output_bytes = out_n*bytes; + int filter_bytes = img_n*bytes; + int width = x; + + STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1); + a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into + if (!a->out) return stbi__err("outofmem", "Out of memory"); + + if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG"); + img_width_bytes = (((img_n * x * depth) + 7) >> 3); + img_len = (img_width_bytes + 1) * y; + + // we used to check for exact match between raw_len and img_len on non-interlaced PNGs, + // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros), + // so just check for raw_len < img_len always. + if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); + + for (j=0; j < y; ++j) { + stbi_uc *cur = a->out + stride*j; + stbi_uc *prior; + int filter = *raw++; + + if (filter > 4) + return stbi__err("invalid filter","Corrupt PNG"); + + if (depth < 8) { + STBI_ASSERT(img_width_bytes <= x); + cur += x*out_n - img_width_bytes; // store output to the rightmost img_len bytes, so we can decode in place + filter_bytes = 1; + width = img_width_bytes; + } + prior = cur - stride; // bugfix: need to compute this after 'cur +=' computation above + + // if first row, use special filter that doesn't sample previous row + if (j == 0) filter = first_row_filter[filter]; + + // handle first byte explicitly + for (k=0; k < filter_bytes; ++k) { + switch (filter) { + case STBI__F_none : cur[k] = raw[k]; break; + case STBI__F_sub : cur[k] = raw[k]; break; + case STBI__F_up : cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; + case STBI__F_avg : cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1)); break; + case STBI__F_paeth : cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(0,prior[k],0)); break; + case STBI__F_avg_first : cur[k] = raw[k]; break; + case STBI__F_paeth_first: cur[k] = raw[k]; break; + } + } + + if (depth == 8) { + if (img_n != out_n) + cur[img_n] = 255; // first pixel + raw += img_n; + cur += out_n; + prior += out_n; + } else if (depth == 16) { + if (img_n != out_n) { + cur[filter_bytes] = 255; // first pixel top byte + cur[filter_bytes+1] = 255; // first pixel bottom byte + } + raw += filter_bytes; + cur += output_bytes; + prior += output_bytes; + } else { + raw += 1; + cur += 1; + prior += 1; + } + + // this is a little gross, so that we don't switch per-pixel or per-component + if (depth < 8 || img_n == out_n) { + int nk = (width - 1)*filter_bytes; + #define STBI__CASE(f) \ + case f: \ + for (k=0; k < nk; ++k) + switch (filter) { + // "none" filter turns into a memcpy here; make that explicit. + case STBI__F_none: memcpy(cur, raw, nk); break; + STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); } break; + STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; + STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); } break; + STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); } break; + STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); } break; + STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); } break; + } + #undef STBI__CASE + raw += nk; + } else { + STBI_ASSERT(img_n+1 == out_n); + #define STBI__CASE(f) \ + case f: \ + for (i=x-1; i >= 1; --i, cur[filter_bytes]=255,raw+=filter_bytes,cur+=output_bytes,prior+=output_bytes) \ + for (k=0; k < filter_bytes; ++k) + switch (filter) { + STBI__CASE(STBI__F_none) { cur[k] = raw[k]; } break; + STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k- output_bytes]); } break; + STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; + STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k- output_bytes])>>1)); } break; + STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],prior[k],prior[k- output_bytes])); } break; + STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k- output_bytes] >> 1)); } break; + STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],0,0)); } break; + } + #undef STBI__CASE + + // the loop above sets the high byte of the pixels' alpha, but for + // 16 bit png files we also need the low byte set. we'll do that here. + if (depth == 16) { + cur = a->out + stride*j; // start at the beginning of the row again + for (i=0; i < x; ++i,cur+=output_bytes) { + cur[filter_bytes+1] = 255; + } + } + } + } + + // we make a separate pass to expand bits to pixels; for performance, + // this could run two scanlines behind the above code, so it won't + // intefere with filtering but will still be in the cache. + if (depth < 8) { + for (j=0; j < y; ++j) { + stbi_uc *cur = a->out + stride*j; + stbi_uc *in = a->out + stride*j + x*out_n - img_width_bytes; + // unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common 8-bit path optimal at minimal cost for 1/2/4-bit + // png guarante byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop + stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range + + // note that the final byte might overshoot and write more data than desired. + // we can allocate enough data that this never writes out of memory, but it + // could also overwrite the next scanline. can it overwrite non-empty data + // on the next scanline? yes, consider 1-pixel-wide scanlines with 1-bit-per-pixel. + // so we need to explicitly clamp the final ones + + if (depth == 4) { + for (k=x*img_n; k >= 2; k-=2, ++in) { + *cur++ = scale * ((*in >> 4) ); + *cur++ = scale * ((*in ) & 0x0f); + } + if (k > 0) *cur++ = scale * ((*in >> 4) ); + } else if (depth == 2) { + for (k=x*img_n; k >= 4; k-=4, ++in) { + *cur++ = scale * ((*in >> 6) ); + *cur++ = scale * ((*in >> 4) & 0x03); + *cur++ = scale * ((*in >> 2) & 0x03); + *cur++ = scale * ((*in ) & 0x03); + } + if (k > 0) *cur++ = scale * ((*in >> 6) ); + if (k > 1) *cur++ = scale * ((*in >> 4) & 0x03); + if (k > 2) *cur++ = scale * ((*in >> 2) & 0x03); + } else if (depth == 1) { + for (k=x*img_n; k >= 8; k-=8, ++in) { + *cur++ = scale * ((*in >> 7) ); + *cur++ = scale * ((*in >> 6) & 0x01); + *cur++ = scale * ((*in >> 5) & 0x01); + *cur++ = scale * ((*in >> 4) & 0x01); + *cur++ = scale * ((*in >> 3) & 0x01); + *cur++ = scale * ((*in >> 2) & 0x01); + *cur++ = scale * ((*in >> 1) & 0x01); + *cur++ = scale * ((*in ) & 0x01); + } + if (k > 0) *cur++ = scale * ((*in >> 7) ); + if (k > 1) *cur++ = scale * ((*in >> 6) & 0x01); + if (k > 2) *cur++ = scale * ((*in >> 5) & 0x01); + if (k > 3) *cur++ = scale * ((*in >> 4) & 0x01); + if (k > 4) *cur++ = scale * ((*in >> 3) & 0x01); + if (k > 5) *cur++ = scale * ((*in >> 2) & 0x01); + if (k > 6) *cur++ = scale * ((*in >> 1) & 0x01); + } + if (img_n != out_n) { + int q; + // insert alpha = 255 + cur = a->out + stride*j; + if (img_n == 1) { + for (q=x-1; q >= 0; --q) { + cur[q*2+1] = 255; + cur[q*2+0] = cur[q]; + } + } else { + STBI_ASSERT(img_n == 3); + for (q=x-1; q >= 0; --q) { + cur[q*4+3] = 255; + cur[q*4+2] = cur[q*3+2]; + cur[q*4+1] = cur[q*3+1]; + cur[q*4+0] = cur[q*3+0]; + } + } + } + } + } else if (depth == 16) { + // force the image data from big-endian to platform-native. + // this is done in a separate pass due to the decoding relying + // on the data being untouched, but could probably be done + // per-line during decode if care is taken. + stbi_uc *cur = a->out; + stbi__uint16 *cur16 = (stbi__uint16*)cur; + + for(i=0; i < x*y*out_n; ++i,cur16++,cur+=2) { + *cur16 = (cur[0] << 8) | cur[1]; + } + } + + return 1; +} + +static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) +{ + int bytes = (depth == 16 ? 2 : 1); + int out_bytes = out_n * bytes; + stbi_uc *final; + int p; + if (!interlaced) + return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); + + // de-interlacing + final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); + for (p=0; p < 7; ++p) { + int xorig[] = { 0,4,0,2,0,1,0 }; + int yorig[] = { 0,0,4,0,2,0,1 }; + int xspc[] = { 8,8,4,4,2,2,1 }; + int yspc[] = { 8,8,8,4,4,2,2 }; + int i,j,x,y; + // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 + x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p]; + y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p]; + if (x && y) { + stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; + if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { + STBI_FREE(final); + return 0; + } + for (j=0; j < y; ++j) { + for (i=0; i < x; ++i) { + int out_y = j*yspc[p]+yorig[p]; + int out_x = i*xspc[p]+xorig[p]; + memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes, + a->out + (j*x+i)*out_bytes, out_bytes); + } + } + STBI_FREE(a->out); + image_data += img_len; + image_data_len -= img_len; + } + } + a->out = final; + + return 1; +} + +static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + // compute color-based transparency, assuming we've + // already got 255 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i=0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 255); + p += 2; + } + } else { + for (i=0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi__uint16 *p = (stbi__uint16*) z->out; + + // compute color-based transparency, assuming we've + // already got 65535 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i = 0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 65535); + p += 2; + } + } else { + for (i = 0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) +{ + stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; + stbi_uc *p, *temp_out, *orig = a->out; + + p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0); + if (p == NULL) return stbi__err("outofmem", "Out of memory"); + + // between here and free(out) below, exitting would leak + temp_out = p; + + if (pal_img_n == 3) { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p += 3; + } + } else { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p[3] = palette[n+3]; + p += 4; + } + } + STBI_FREE(a->out); + a->out = temp_out; + + STBI_NOTUSED(len); + + return 1; +} + +static int stbi__unpremultiply_on_load = 0; +static int stbi__de_iphone_flag = 0; + +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag = flag_true_if_should_convert; +} + +static void stbi__de_iphone(stbi__png *z) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + if (s->img_out_n == 3) { // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 3; + } + } else { + STBI_ASSERT(s->img_out_n == 4); + if (stbi__unpremultiply_on_load) { + // convert bgr to rgb and unpremultiply + for (i=0; i < pixel_count; ++i) { + stbi_uc a = p[3]; + stbi_uc t = p[0]; + if (a) { + stbi_uc half = a / 2; + p[0] = (p[2] * 255 + half) / a; + p[1] = (p[1] * 255 + half) / a; + p[2] = ( t * 255 + half) / a; + } else { + p[0] = p[2]; + p[2] = t; + } + p += 4; + } + } else { + // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 4; + } + } + } +} + +#define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d)) + +static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) +{ + stbi_uc palette[1024], pal_img_n=0; + stbi_uc has_trans=0, tc[3]; + stbi__uint16 tc16[3]; + stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0; + int first=1,k,interlace=0, color=0, is_iphone=0; + stbi__context *s = z->s; + + z->expanded = NULL; + z->idata = NULL; + z->out = NULL; + + if (!stbi__check_png_header(s)) return 0; + + if (scan == STBI__SCAN_type) return 1; + + for (;;) { + stbi__pngchunk c = stbi__get_chunk_header(s); + switch (c.type) { + case STBI__PNG_TYPE('C','g','B','I'): + is_iphone = 1; + stbi__skip(s, c.length); + break; + case STBI__PNG_TYPE('I','H','D','R'): { + int comp,filter; + if (!first) return stbi__err("multiple IHDR","Corrupt PNG"); + first = 0; + if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG"); + s->img_x = stbi__get32be(s); if (s->img_x > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)"); + s->img_y = stbi__get32be(s); if (s->img_y > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)"); + z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only"); + color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG"); + comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG"); + filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG"); + interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG"); + if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG"); + if (!pal_img_n) { + s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); + if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); + if (scan == STBI__SCAN_header) return 1; + } else { + // if paletted, then pal_n is our final components, and + // img_n is # components to decompress/filter. + s->img_n = 1; + if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG"); + // if SCAN_header, have to scan to see if we have a tRNS + } + break; + } + + case STBI__PNG_TYPE('P','L','T','E'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG"); + pal_len = c.length / 3; + if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG"); + for (i=0; i < pal_len; ++i) { + palette[i*4+0] = stbi__get8(s); + palette[i*4+1] = stbi__get8(s); + palette[i*4+2] = stbi__get8(s); + palette[i*4+3] = 255; + } + break; + } + + case STBI__PNG_TYPE('t','R','N','S'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG"); + if (pal_img_n) { + if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } + if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG"); + if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG"); + pal_img_n = 4; + for (i=0; i < c.length; ++i) + palette[i*4+3] = stbi__get8(s); + } else { + if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG"); + if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG"); + has_trans = 1; + if (z->depth == 16) { + for (k = 0; k < s->img_n; ++k) tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is + } else { + for (k = 0; k < s->img_n; ++k) tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger + } + } + break; + } + + case STBI__PNG_TYPE('I','D','A','T'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG"); + if (scan == STBI__SCAN_header) { s->img_n = pal_img_n; return 1; } + if ((int)(ioff + c.length) < (int)ioff) return 0; + if (ioff + c.length > idata_limit) { + stbi__uint32 idata_limit_old = idata_limit; + stbi_uc *p; + if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; + while (ioff + c.length > idata_limit) + idata_limit *= 2; + STBI_NOTUSED(idata_limit_old); + p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); + z->idata = p; + } + if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG"); + ioff += c.length; + break; + } + + case STBI__PNG_TYPE('I','E','N','D'): { + stbi__uint32 raw_len, bpl; + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (scan != STBI__SCAN_load) return 1; + if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG"); + // initial guess for decoded data size to avoid unnecessary reallocs + bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component + raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; + z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); + if (z->expanded == NULL) return 0; // zlib should set error + STBI_FREE(z->idata); z->idata = NULL; + if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans) + s->img_out_n = s->img_n+1; + else + s->img_out_n = s->img_n; + if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0; + if (has_trans) { + if (z->depth == 16) { + if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; + } else { + if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; + } + } + if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) + stbi__de_iphone(z); + if (pal_img_n) { + // pal_img_n == 3 or 4 + s->img_n = pal_img_n; // record the actual colors we had + s->img_out_n = pal_img_n; + if (req_comp >= 3) s->img_out_n = req_comp; + if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) + return 0; + } else if (has_trans) { + // non-paletted image with tRNS -> source image has (constant) alpha + ++s->img_n; + } + STBI_FREE(z->expanded); z->expanded = NULL; + return 1; + } + + default: + // if critical, fail + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if ((c.type & (1 << 29)) == 0) { + #ifndef STBI_NO_FAILURE_STRINGS + // not threadsafe + static char invalid_chunk[] = "XXXX PNG chunk not known"; + invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); + invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); + invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); + invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); + #endif + return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); + } + stbi__skip(s, c.length); + break; + } + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + } +} + +static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri) +{ + void *result=NULL; + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { + if (p->depth < 8) + ri->bits_per_channel = 8; + else + ri->bits_per_channel = p->depth; + result = p->out; + p->out = NULL; + if (req_comp && req_comp != p->s->img_out_n) { + if (ri->bits_per_channel == 8) + result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + else + result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + p->s->img_out_n = req_comp; + if (result == NULL) return result; + } + *x = p->s->img_x; + *y = p->s->img_y; + if (n) *n = p->s->img_n; + } + STBI_FREE(p->out); p->out = NULL; + STBI_FREE(p->expanded); p->expanded = NULL; + STBI_FREE(p->idata); p->idata = NULL; + + return result; +} + +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi__png p; + p.s = s; + return stbi__do_png(&p, x,y,comp,req_comp, ri); +} + +static int stbi__png_test(stbi__context *s) +{ + int r; + r = stbi__check_png_header(s); + stbi__rewind(s); + return r; +} + +static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) +{ + if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { + stbi__rewind( p->s ); + return 0; + } + if (x) *x = p->s->img_x; + if (y) *y = p->s->img_y; + if (comp) *comp = p->s->img_n; + return 1; +} + +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__png p; + p.s = s; + return stbi__png_info_raw(&p, x, y, comp); +} + +static int stbi__png_is16(stbi__context *s) +{ + stbi__png p; + p.s = s; + if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) + return 0; + if (p.depth != 16) { + stbi__rewind(p.s); + return 0; + } + return 1; +} +#endif + +// Microsoft/Windows BMP image + +#ifndef STBI_NO_BMP +static int stbi__bmp_test_raw(stbi__context *s) +{ + int r; + int sz; + if (stbi__get8(s) != 'B') return 0; + if (stbi__get8(s) != 'M') return 0; + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + stbi__get32le(s); // discard data offset + sz = stbi__get32le(s); + r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); + return r; +} + +static int stbi__bmp_test(stbi__context *s) +{ + int r = stbi__bmp_test_raw(s); + stbi__rewind(s); + return r; +} + + +// returns 0..31 for the highest set bit +static int stbi__high_bit(unsigned int z) +{ + int n=0; + if (z == 0) return -1; + if (z >= 0x10000) n += 16, z >>= 16; + if (z >= 0x00100) n += 8, z >>= 8; + if (z >= 0x00010) n += 4, z >>= 4; + if (z >= 0x00004) n += 2, z >>= 2; + if (z >= 0x00002) n += 1, z >>= 1; + return n; +} + +static int stbi__bitcount(unsigned int a) +{ + a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 + a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 + a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits + a = (a + (a >> 8)); // max 16 per 8 bits + a = (a + (a >> 16)); // max 32 per 8 bits + return a & 0xff; +} + +// extract an arbitrarily-aligned N-bit value (N=bits) +// from v, and then make it 8-bits long and fractionally +// extend it to full full range. +static int stbi__shiftsigned(int v, int shift, int bits) +{ + static unsigned int mul_table[9] = { + 0, + 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/, + 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/, + }; + static unsigned int shift_table[9] = { + 0, 0,0,1,0,2,4,6,0, + }; + if (shift < 0) + v <<= -shift; + else + v >>= shift; + STBI_ASSERT(v >= 0 && v < 256); + v >>= (8-bits); + STBI_ASSERT(bits >= 0 && bits <= 8); + return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits]; +} + +typedef struct +{ + int bpp, offset, hsz; + unsigned int mr,mg,mb,ma, all_a; +} stbi__bmp_data; + +static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) +{ + int hsz; + if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + info->offset = stbi__get32le(s); + info->hsz = hsz = stbi__get32le(s); + info->mr = info->mg = info->mb = info->ma = 0; + + if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); + if (hsz == 12) { + s->img_x = stbi__get16le(s); + s->img_y = stbi__get16le(s); + } else { + s->img_x = stbi__get32le(s); + s->img_y = stbi__get32le(s); + } + if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); + info->bpp = stbi__get16le(s); + if (hsz != 12) { + int compress = stbi__get32le(s); + if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); + stbi__get32le(s); // discard sizeof + stbi__get32le(s); // discard hres + stbi__get32le(s); // discard vres + stbi__get32le(s); // discard colorsused + stbi__get32le(s); // discard max important + if (hsz == 40 || hsz == 56) { + if (hsz == 56) { + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + } + if (info->bpp == 16 || info->bpp == 32) { + if (compress == 0) { + if (info->bpp == 32) { + info->mr = 0xffu << 16; + info->mg = 0xffu << 8; + info->mb = 0xffu << 0; + info->ma = 0xffu << 24; + info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 + } else { + info->mr = 31u << 10; + info->mg = 31u << 5; + info->mb = 31u << 0; + } + } else if (compress == 3) { + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + // not documented, but generated by photoshop and handled by mspaint + if (info->mr == info->mg && info->mg == info->mb) { + // ?!?!? + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else { + int i; + if (hsz != 108 && hsz != 124) + return stbi__errpuc("bad BMP", "bad BMP"); + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->ma = stbi__get32le(s); + stbi__get32le(s); // discard color space + for (i=0; i < 12; ++i) + stbi__get32le(s); // discard color space parameters + if (hsz == 124) { + stbi__get32le(s); // discard rendering intent + stbi__get32le(s); // discard offset of profile data + stbi__get32le(s); // discard size of profile data + stbi__get32le(s); // discard reserved + } + } + } + return (void *) 1; +} + + +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + unsigned int mr=0,mg=0,mb=0,ma=0, all_a; + stbi_uc pal[256][4]; + int psize=0,i,j,width; + int flip_vertically, pad, target; + stbi__bmp_data info; + STBI_NOTUSED(ri); + + info.all_a = 255; + if (stbi__bmp_parse_header(s, &info) == NULL) + return NULL; // error code already set + + flip_vertically = ((int) s->img_y) > 0; + s->img_y = abs((int) s->img_y); + + mr = info.mr; + mg = info.mg; + mb = info.mb; + ma = info.ma; + all_a = info.all_a; + + if (info.hsz == 12) { + if (info.bpp < 24) + psize = (info.offset - 14 - 24) / 3; + } else { + if (info.bpp < 16) + psize = (info.offset - 14 - info.hsz) >> 2; + } + + s->img_n = ma ? 4 : 3; + if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 + target = req_comp; + else + target = s->img_n; // if they want monochrome, we'll post-convert + + // sanity-check size + if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) + return stbi__errpuc("too large", "Corrupt BMP"); + + out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (info.bpp < 16) { + int z=0; + if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } + for (i=0; i < psize; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + if (info.hsz != 12) stbi__get8(s); + pal[i][3] = 255; + } + stbi__skip(s, info.offset - 14 - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); + if (info.bpp == 1) width = (s->img_x + 7) >> 3; + else if (info.bpp == 4) width = (s->img_x + 1) >> 1; + else if (info.bpp == 8) width = s->img_x; + else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } + pad = (-width)&3; + if (info.bpp == 1) { + for (j=0; j < (int) s->img_y; ++j) { + int bit_offset = 7, v = stbi__get8(s); + for (i=0; i < (int) s->img_x; ++i) { + int color = (v>>bit_offset)&0x1; + out[z++] = pal[color][0]; + out[z++] = pal[color][1]; + out[z++] = pal[color][2]; + if((--bit_offset) < 0) { + bit_offset = 7; + v = stbi__get8(s); + } + } + stbi__skip(s, pad); + } + } else { + for (j=0; j < (int) s->img_y; ++j) { + for (i=0; i < (int) s->img_x; i += 2) { + int v=stbi__get8(s),v2=0; + if (info.bpp == 4) { + v2 = v & 15; + v >>= 4; + } + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + v = (info.bpp == 8) ? stbi__get8(s) : v2; + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + } + stbi__skip(s, pad); + } + } + } else { + int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; + int z = 0; + int easy=0; + stbi__skip(s, info.offset - 14 - info.hsz); + if (info.bpp == 24) width = 3 * s->img_x; + else if (info.bpp == 16) width = 2*s->img_x; + else /* bpp = 32 and pad = 0 */ width=0; + pad = (-width) & 3; + if (info.bpp == 24) { + easy = 1; + } else if (info.bpp == 32) { + if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) + easy = 2; + } + if (!easy) { + if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } + // right shift amt to put high bit in position #7 + rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr); + gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg); + bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb); + ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma); + } + for (j=0; j < (int) s->img_y; ++j) { + if (easy) { + for (i=0; i < (int) s->img_x; ++i) { + unsigned char a; + out[z+2] = stbi__get8(s); + out[z+1] = stbi__get8(s); + out[z+0] = stbi__get8(s); + z += 3; + a = (easy == 2 ? stbi__get8(s) : 255); + all_a |= a; + if (target == 4) out[z++] = a; + } + } else { + int bpp = info.bpp; + for (i=0; i < (int) s->img_x; ++i) { + stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s)); + unsigned int a; + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); + a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); + all_a |= a; + if (target == 4) out[z++] = STBI__BYTECAST(a); + } + } + stbi__skip(s, pad); + } + } + + // if alpha channel is all 0s, replace with all 255s + if (target == 4 && all_a == 0) + for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4) + out[i] = 255; + + if (flip_vertically) { + stbi_uc t; + for (j=0; j < (int) s->img_y>>1; ++j) { + stbi_uc *p1 = out + j *s->img_x*target; + stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; + for (i=0; i < (int) s->img_x*target; ++i) { + t = p1[i], p1[i] = p2[i], p2[i] = t; + } + } + } + + if (req_comp && req_comp != target) { + out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + return out; +} +#endif + +// Targa Truevision - TGA +// by Jonathan Dummer +#ifndef STBI_NO_TGA +// returns STBI_rgb or whatever, 0 on error +static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) +{ + // only RGB or RGBA (incl. 16bit) or grey allowed + if (is_rgb16) *is_rgb16 = 0; + switch(bits_per_pixel) { + case 8: return STBI_grey; + case 16: if(is_grey) return STBI_grey_alpha; + // fallthrough + case 15: if(is_rgb16) *is_rgb16 = 1; + return STBI_rgb; + case 24: // fallthrough + case 32: return bits_per_pixel/8; + default: return 0; + } +} + +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) +{ + int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; + int sz, tga_colormap_type; + stbi__get8(s); // discard Offset + tga_colormap_type = stbi__get8(s); // colormap type + if( tga_colormap_type > 1 ) { + stbi__rewind(s); + return 0; // only RGB or indexed allowed + } + tga_image_type = stbi__get8(s); // image type + if ( tga_colormap_type == 1 ) { // colormapped (paletted) image + if (tga_image_type != 1 && tga_image_type != 9) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip image x and y origin + tga_colormap_bpp = sz; + } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE + if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) { + stbi__rewind(s); + return 0; // only RGB or grey allowed, +/- RLE + } + stbi__skip(s,9); // skip colormap specification and image x/y origin + tga_colormap_bpp = 0; + } + tga_w = stbi__get16le(s); + if( tga_w < 1 ) { + stbi__rewind(s); + return 0; // test width + } + tga_h = stbi__get16le(s); + if( tga_h < 1 ) { + stbi__rewind(s); + return 0; // test height + } + tga_bits_per_pixel = stbi__get8(s); // bits per pixel + stbi__get8(s); // ignore alpha bits + if (tga_colormap_bpp != 0) { + if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { + // when using a colormap, tga_bits_per_pixel is the size of the indexes + // I don't think anything but 8 or 16bit indexes makes sense + stbi__rewind(s); + return 0; + } + tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); + } else { + tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); + } + if(!tga_comp) { + stbi__rewind(s); + return 0; + } + if (x) *x = tga_w; + if (y) *y = tga_h; + if (comp) *comp = tga_comp; + return 1; // seems to have passed everything +} + +static int stbi__tga_test(stbi__context *s) +{ + int res = 0; + int sz, tga_color_type; + stbi__get8(s); // discard Offset + tga_color_type = stbi__get8(s); // color type + if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed + sz = stbi__get8(s); // image type + if ( tga_color_type == 1 ) { // colormapped (paletted) image + if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + stbi__skip(s,4); // skip image x and y origin + } else { // "normal" image w/o colormap + if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE + stbi__skip(s,9); // skip colormap specification and image x/y origin + } + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height + sz = stbi__get8(s); // bits per pixel + if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + + res = 1; // if we got this far, everything's good and we can return 1 instead of 0 + +errorEnd: + stbi__rewind(s); + return res; +} + +// read 16bit value and convert to 24bit RGB +static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) +{ + stbi__uint16 px = (stbi__uint16)stbi__get16le(s); + stbi__uint16 fiveBitMask = 31; + // we have 3 channels with 5bits each + int r = (px >> 10) & fiveBitMask; + int g = (px >> 5) & fiveBitMask; + int b = px & fiveBitMask; + // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later + out[0] = (stbi_uc)((r * 255)/31); + out[1] = (stbi_uc)((g * 255)/31); + out[2] = (stbi_uc)((b * 255)/31); + + // some people claim that the most significant bit might be used for alpha + // (possibly if an alpha-bit is set in the "image descriptor byte") + // but that only made 16bit test images completely translucent.. + // so let's treat all 15 and 16bit TGAs as RGB with no alpha. +} + +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + // read in the TGA header stuff + int tga_offset = stbi__get8(s); + int tga_indexed = stbi__get8(s); + int tga_image_type = stbi__get8(s); + int tga_is_RLE = 0; + int tga_palette_start = stbi__get16le(s); + int tga_palette_len = stbi__get16le(s); + int tga_palette_bits = stbi__get8(s); + int tga_x_origin = stbi__get16le(s); + int tga_y_origin = stbi__get16le(s); + int tga_width = stbi__get16le(s); + int tga_height = stbi__get16le(s); + int tga_bits_per_pixel = stbi__get8(s); + int tga_comp, tga_rgb16=0; + int tga_inverted = stbi__get8(s); + // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) + // image data + unsigned char *tga_data; + unsigned char *tga_palette = NULL; + int i, j; + unsigned char raw_data[4] = {0}; + int RLE_count = 0; + int RLE_repeating = 0; + int read_next_pixel = 1; + STBI_NOTUSED(ri); + + // do a tiny bit of precessing + if ( tga_image_type >= 8 ) + { + tga_image_type -= 8; + tga_is_RLE = 1; + } + tga_inverted = 1 - ((tga_inverted >> 5) & 1); + + // If I'm paletted, then I'll use the number of bits from the palette + if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); + else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); + + if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency + return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); + + // tga info + *x = tga_width; + *y = tga_height; + if (comp) *comp = tga_comp; + + if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) + return stbi__errpuc("too large", "Corrupt TGA"); + + tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); + if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); + + // skip to the data's starting position (offset usually = 0) + stbi__skip(s, tga_offset ); + + if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) { + for (i=0; i < tga_height; ++i) { + int row = tga_inverted ? tga_height -i - 1 : i; + stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; + stbi__getn(s, tga_row, tga_width * tga_comp); + } + } else { + // do I need to load a palette? + if ( tga_indexed) + { + // any data to skip? (offset usually = 0) + stbi__skip(s, tga_palette_start ); + // load the palette + tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); + if (!tga_palette) { + STBI_FREE(tga_data); + return stbi__errpuc("outofmem", "Out of memory"); + } + if (tga_rgb16) { + stbi_uc *pal_entry = tga_palette; + STBI_ASSERT(tga_comp == STBI_rgb); + for (i=0; i < tga_palette_len; ++i) { + stbi__tga_read_rgb16(s, pal_entry); + pal_entry += tga_comp; + } + } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { + STBI_FREE(tga_data); + STBI_FREE(tga_palette); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + } + // load the data + for (i=0; i < tga_width * tga_height; ++i) + { + // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? + if ( tga_is_RLE ) + { + if ( RLE_count == 0 ) + { + // yep, get the next byte as a RLE command + int RLE_cmd = stbi__get8(s); + RLE_count = 1 + (RLE_cmd & 127); + RLE_repeating = RLE_cmd >> 7; + read_next_pixel = 1; + } else if ( !RLE_repeating ) + { + read_next_pixel = 1; + } + } else + { + read_next_pixel = 1; + } + // OK, if I need to read a pixel, do it now + if ( read_next_pixel ) + { + // load however much data we did have + if ( tga_indexed ) + { + // read in index, then perform the lookup + int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); + if ( pal_idx >= tga_palette_len ) { + // invalid index + pal_idx = 0; + } + pal_idx *= tga_comp; + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = tga_palette[pal_idx+j]; + } + } else if(tga_rgb16) { + STBI_ASSERT(tga_comp == STBI_rgb); + stbi__tga_read_rgb16(s, raw_data); + } else { + // read in the data raw + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = stbi__get8(s); + } + } + // clear the reading flag for the next pixel + read_next_pixel = 0; + } // end of reading a pixel + + // copy data + for (j = 0; j < tga_comp; ++j) + tga_data[i*tga_comp+j] = raw_data[j]; + + // in case we're in RLE mode, keep counting down + --RLE_count; + } + // do I need to invert the image? + if ( tga_inverted ) + { + for (j = 0; j*2 < tga_height; ++j) + { + int index1 = j * tga_width * tga_comp; + int index2 = (tga_height - 1 - j) * tga_width * tga_comp; + for (i = tga_width * tga_comp; i > 0; --i) + { + unsigned char temp = tga_data[index1]; + tga_data[index1] = tga_data[index2]; + tga_data[index2] = temp; + ++index1; + ++index2; + } + } + } + // clear my palette, if I had one + if ( tga_palette != NULL ) + { + STBI_FREE( tga_palette ); + } + } + + // swap RGB - if the source data was RGB16, it already is in the right order + if (tga_comp >= 3 && !tga_rgb16) + { + unsigned char* tga_pixel = tga_data; + for (i=0; i < tga_width * tga_height; ++i) + { + unsigned char temp = tga_pixel[0]; + tga_pixel[0] = tga_pixel[2]; + tga_pixel[2] = temp; + tga_pixel += tga_comp; + } + } + + // convert to target component count + if (req_comp && req_comp != tga_comp) + tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); + + // the things I do to get rid of an error message, and yet keep + // Microsoft's C compilers happy... [8^( + tga_palette_start = tga_palette_len = tga_palette_bits = + tga_x_origin = tga_y_origin = 0; + // OK, done + return tga_data; +} +#endif + +// ************************************************************************************************* +// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s) +{ + int r = (stbi__get32be(s) == 0x38425053); + stbi__rewind(s); + return r; +} + +static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount) +{ + int count, nleft, len; + + count = 0; + while ((nleft = pixelCount - count) > 0) { + len = stbi__get8(s); + if (len == 128) { + // No-op. + } else if (len < 128) { + // Copy next len+1 bytes literally. + len++; + if (len > nleft) return 0; // corrupt data + count += len; + while (len) { + *p = stbi__get8(s); + p += 4; + len--; + } + } else if (len > 128) { + stbi_uc val; + // Next -len+1 bytes in the dest are replicated from next source byte. + // (Interpret len as a negative 8-bit int.) + len = 257 - len; + if (len > nleft) return 0; // corrupt data + val = stbi__get8(s); + count += len; + while (len) { + *p = val; + p += 4; + len--; + } + } + } + + return 1; +} + +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + int pixelCount; + int channelCount, compression; + int channel, i; + int bitdepth; + int w,h; + stbi_uc *out; + STBI_NOTUSED(ri); + + // Check identifier + if (stbi__get32be(s) != 0x38425053) // "8BPS" + return stbi__errpuc("not PSD", "Corrupt PSD image"); + + // Check file type version. + if (stbi__get16be(s) != 1) + return stbi__errpuc("wrong version", "Unsupported version of PSD image"); + + // Skip 6 reserved bytes. + stbi__skip(s, 6 ); + + // Read the number of channels (R, G, B, A, etc). + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) + return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); + + // Read the rows and columns of the image. + h = stbi__get32be(s); + w = stbi__get32be(s); + + // Make sure the depth is 8 bits. + bitdepth = stbi__get16be(s); + if (bitdepth != 8 && bitdepth != 16) + return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); + + // Make sure the color mode is RGB. + // Valid options are: + // 0: Bitmap + // 1: Grayscale + // 2: Indexed color + // 3: RGB color + // 4: CMYK color + // 7: Multichannel + // 8: Duotone + // 9: Lab color + if (stbi__get16be(s) != 3) + return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); + + // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) + stbi__skip(s,stbi__get32be(s) ); + + // Skip the image resources. (resolution, pen tool paths, etc) + stbi__skip(s, stbi__get32be(s) ); + + // Skip the reserved data. + stbi__skip(s, stbi__get32be(s) ); + + // Find out if the data is compressed. + // Known values: + // 0: no compression + // 1: RLE compressed + compression = stbi__get16be(s); + if (compression > 1) + return stbi__errpuc("bad compression", "PSD has an unknown compression format"); + + // Check size + if (!stbi__mad3sizes_valid(4, w, h, 0)) + return stbi__errpuc("too large", "Corrupt PSD"); + + // Create the destination image. + + if (!compression && bitdepth == 16 && bpc == 16) { + out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0); + ri->bits_per_channel = 16; + } else + out = (stbi_uc *) stbi__malloc(4 * w*h); + + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + pixelCount = w*h; + + // Initialize the data to zero. + //memset( out, 0, pixelCount * 4 ); + + // Finally, the image data. + if (compression) { + // RLE as used by .PSD and .TIFF + // Loop until you get the number of unpacked bytes you are expecting: + // Read the next source byte into n. + // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. + // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. + // Else if n is 128, noop. + // Endloop + + // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data, + // which we're going to just skip. + stbi__skip(s, h * channelCount * 2 ); + + // Read the RLE data by channel. + for (channel = 0; channel < 4; channel++) { + stbi_uc *p; + + p = out+channel; + if (channel >= channelCount) { + // Fill this channel with default data. + for (i = 0; i < pixelCount; i++, p += 4) + *p = (channel == 3 ? 255 : 0); + } else { + // Read the RLE data. + if (!stbi__psd_decode_rle(s, p, pixelCount)) { + STBI_FREE(out); + return stbi__errpuc("corrupt", "bad RLE data"); + } + } + } + + } else { + // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) + // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image. + + // Read the data by channel. + for (channel = 0; channel < 4; channel++) { + if (channel >= channelCount) { + // Fill this channel with default data. + if (bitdepth == 16 && bpc == 16) { + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + stbi__uint16 val = channel == 3 ? 65535 : 0; + for (i = 0; i < pixelCount; i++, q += 4) + *q = val; + } else { + stbi_uc *p = out+channel; + stbi_uc val = channel == 3 ? 255 : 0; + for (i = 0; i < pixelCount; i++, p += 4) + *p = val; + } + } else { + if (ri->bits_per_channel == 16) { // output bpc + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + for (i = 0; i < pixelCount; i++, q += 4) + *q = (stbi__uint16) stbi__get16be(s); + } else { + stbi_uc *p = out+channel; + if (bitdepth == 16) { // input bpc + for (i = 0; i < pixelCount; i++, p += 4) + *p = (stbi_uc) (stbi__get16be(s) >> 8); + } else { + for (i = 0; i < pixelCount; i++, p += 4) + *p = stbi__get8(s); + } + } + } + } + } + + // remove weird white matte from PSD + if (channelCount >= 4) { + if (ri->bits_per_channel == 16) { + for (i=0; i < w*h; ++i) { + stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i; + if (pixel[3] != 0 && pixel[3] != 65535) { + float a = pixel[3] / 65535.0f; + float ra = 1.0f / a; + float inv_a = 65535.0f * (1 - ra); + pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a); + pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a); + pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a); + } + } + } else { + for (i=0; i < w*h; ++i) { + unsigned char *pixel = out + 4*i; + if (pixel[3] != 0 && pixel[3] != 255) { + float a = pixel[3] / 255.0f; + float ra = 1.0f / a; + float inv_a = 255.0f * (1 - ra); + pixel[0] = (unsigned char) (pixel[0]*ra + inv_a); + pixel[1] = (unsigned char) (pixel[1]*ra + inv_a); + pixel[2] = (unsigned char) (pixel[2]*ra + inv_a); + } + } + } + } + + // convert to desired output format + if (req_comp && req_comp != 4) { + if (ri->bits_per_channel == 16) + out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h); + else + out = stbi__convert_format(out, 4, req_comp, w, h); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + if (comp) *comp = 4; + *y = h; + *x = w; + + return out; +} +#endif + +// ************************************************************************************************* +// Softimage PIC loader +// by Tom Seddon +// +// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format +// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ + +#ifndef STBI_NO_PIC +static int stbi__pic_is4(stbi__context *s,const char *str) +{ + int i; + for (i=0; i<4; ++i) + if (stbi__get8(s) != (stbi_uc)str[i]) + return 0; + + return 1; +} + +static int stbi__pic_test_core(stbi__context *s) +{ + int i; + + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) + return 0; + + for(i=0;i<84;++i) + stbi__get8(s); + + if (!stbi__pic_is4(s,"PICT")) + return 0; + + return 1; +} + +typedef struct +{ + stbi_uc size,type,channel; +} stbi__pic_packet; + +static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest) +{ + int mask=0x80, i; + + for (i=0; i<4; ++i, mask>>=1) { + if (channel & mask) { + if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short"); + dest[i]=stbi__get8(s); + } + } + + return dest; +} + +static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src) +{ + int mask=0x80,i; + + for (i=0;i<4; ++i, mask>>=1) + if (channel&mask) + dest[i]=src[i]; +} + +static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result) +{ + int act_comp=0,num_packets=0,y,chained; + stbi__pic_packet packets[10]; + + // this will (should...) cater for even some bizarre stuff like having data + // for the same channel in multiple packets. + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return stbi__errpuc("bad format","too many packets"); + + packet = &packets[num_packets++]; + + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + + act_comp |= packet->channel; + + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)"); + if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp"); + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? + + for(y=0; ytype) { + default: + return stbi__errpuc("bad format","packet has bad compression type"); + + case 0: {//uncompressed + int x; + + for(x=0;xchannel,dest)) + return 0; + break; + } + + case 1://Pure RLE + { + int left=width, i; + + while (left>0) { + stbi_uc count,value[4]; + + count=stbi__get8(s); + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)"); + + if (count > left) + count = (stbi_uc) left; + + if (!stbi__readval(s,packet->channel,value)) return 0; + + for(i=0; ichannel,dest,value); + left -= count; + } + } + break; + + case 2: {//Mixed RLE + int left=width; + while (left>0) { + int count = stbi__get8(s), i; + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)"); + + if (count >= 128) { // Repeated + stbi_uc value[4]; + + if (count==128) + count = stbi__get16be(s); + else + count -= 127; + if (count > left) + return stbi__errpuc("bad file","scanline overrun"); + + if (!stbi__readval(s,packet->channel,value)) + return 0; + + for(i=0;ichannel,dest,value); + } else { // Raw + ++count; + if (count>left) return stbi__errpuc("bad file","scanline overrun"); + + for(i=0;ichannel,dest)) + return 0; + } + left-=count; + } + break; + } + } + } + } + + return result; +} + +static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri) +{ + stbi_uc *result; + int i, x,y, internal_comp; + STBI_NOTUSED(ri); + + if (!comp) comp = &internal_comp; + + for (i=0; i<92; ++i) + stbi__get8(s); + + x = stbi__get16be(s); + y = stbi__get16be(s); + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)"); + if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); + + stbi__get32be(s); //skip `ratio' + stbi__get16be(s); //skip `fields' + stbi__get16be(s); //skip `pad' + + // intermediate buffer is RGBA + result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0); + memset(result, 0xff, x*y*4); + + if (!stbi__pic_load_core(s,x,y,comp, result)) { + STBI_FREE(result); + result=0; + } + *px = x; + *py = y; + if (req_comp == 0) req_comp = *comp; + result=stbi__convert_format(result,4,req_comp,x,y); + + return result; +} + +static int stbi__pic_test(stbi__context *s) +{ + int r = stbi__pic_test_core(s); + stbi__rewind(s); + return r; +} +#endif + +// ************************************************************************************************* +// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb + +#ifndef STBI_NO_GIF +typedef struct +{ + stbi__int16 prefix; + stbi_uc first; + stbi_uc suffix; +} stbi__gif_lzw; + +typedef struct +{ + int w,h; + stbi_uc *out; // output buffer (always 4 components) + stbi_uc *background; // The current "background" as far as a gif is concerned + stbi_uc *history; + int flags, bgindex, ratio, transparent, eflags; + stbi_uc pal[256][4]; + stbi_uc lpal[256][4]; + stbi__gif_lzw codes[8192]; + stbi_uc *color_table; + int parse, step; + int lflags; + int start_x, start_y; + int max_x, max_y; + int cur_x, cur_y; + int line_size; + int delay; +} stbi__gif; + +static int stbi__gif_test_raw(stbi__context *s) +{ + int sz; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; + sz = stbi__get8(s); + if (sz != '9' && sz != '7') return 0; + if (stbi__get8(s) != 'a') return 0; + return 1; +} + +static int stbi__gif_test(stbi__context *s) +{ + int r = stbi__gif_test_raw(s); + stbi__rewind(s); + return r; +} + +static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp) +{ + int i; + for (i=0; i < num_entries; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + pal[i][3] = transp == i ? 0 : 255; + } +} + +static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info) +{ + stbi_uc version; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') + return stbi__err("not GIF", "Corrupt GIF"); + + version = stbi__get8(s); + if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); + if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); + + stbi__g_failure_reason = ""; + g->w = stbi__get16le(s); + g->h = stbi__get16le(s); + g->flags = stbi__get8(s); + g->bgindex = stbi__get8(s); + g->ratio = stbi__get8(s); + g->transparent = -1; + + if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments + + if (is_info) return 1; + + if (g->flags & 0x80) + stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1); + + return 1; +} + +static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif)); + if (!stbi__gif_header(s, g, comp, 1)) { + STBI_FREE(g); + stbi__rewind( s ); + return 0; + } + if (x) *x = g->w; + if (y) *y = g->h; + STBI_FREE(g); + return 1; +} + +static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) +{ + stbi_uc *p, *c; + int idx; + + // recurse to decode the prefixes, since the linked-list is backwards, + // and working backwards through an interleaved image would be nasty + if (g->codes[code].prefix >= 0) + stbi__out_gif_code(g, g->codes[code].prefix); + + if (g->cur_y >= g->max_y) return; + + idx = g->cur_x + g->cur_y; + p = &g->out[idx]; + g->history[idx / 4] = 1; + + c = &g->color_table[g->codes[code].suffix * 4]; + if (c[3] > 128) { // don't render transparent pixels; + p[0] = c[2]; + p[1] = c[1]; + p[2] = c[0]; + p[3] = c[3]; + } + g->cur_x += 4; + + if (g->cur_x >= g->max_x) { + g->cur_x = g->start_x; + g->cur_y += g->step; + + while (g->cur_y >= g->max_y && g->parse > 0) { + g->step = (1 << g->parse) * g->line_size; + g->cur_y = g->start_y + (g->step >> 1); + --g->parse; + } + } +} + +static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) +{ + stbi_uc lzw_cs; + stbi__int32 len, init_code; + stbi__uint32 first; + stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; + stbi__gif_lzw *p; + + lzw_cs = stbi__get8(s); + if (lzw_cs > 12) return NULL; + clear = 1 << lzw_cs; + first = 1; + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + bits = 0; + valid_bits = 0; + for (init_code = 0; init_code < clear; init_code++) { + g->codes[init_code].prefix = -1; + g->codes[init_code].first = (stbi_uc) init_code; + g->codes[init_code].suffix = (stbi_uc) init_code; + } + + // support no starting clear code + avail = clear+2; + oldcode = -1; + + len = 0; + for(;;) { + if (valid_bits < codesize) { + if (len == 0) { + len = stbi__get8(s); // start new block + if (len == 0) + return g->out; + } + --len; + bits |= (stbi__int32) stbi__get8(s) << valid_bits; + valid_bits += 8; + } else { + stbi__int32 code = bits & codemask; + bits >>= codesize; + valid_bits -= codesize; + // @OPTIMIZE: is there some way we can accelerate the non-clear path? + if (code == clear) { // clear code + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + avail = clear + 2; + oldcode = -1; + first = 0; + } else if (code == clear + 1) { // end of stream code + stbi__skip(s, len); + while ((len = stbi__get8(s)) > 0) + stbi__skip(s,len); + return g->out; + } else if (code <= avail) { + if (first) { + return stbi__errpuc("no clear code", "Corrupt GIF"); + } + + if (oldcode >= 0) { + p = &g->codes[avail++]; + if (avail > 8192) { + return stbi__errpuc("too many codes", "Corrupt GIF"); + } + + p->prefix = (stbi__int16) oldcode; + p->first = g->codes[oldcode].first; + p->suffix = (code == avail) ? p->first : g->codes[code].first; + } else if (code == avail) + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + + stbi__out_gif_code(g, (stbi__uint16) code); + + if ((avail & codemask) == 0 && avail <= 0x0FFF) { + codesize++; + codemask = (1 << codesize) - 1; + } + + oldcode = code; + } else { + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + } + } + } +} + +// this function is designed to support animated gifs, although stb_image doesn't support it +// two back is the image from two frames ago, used for a very specific disposal format +static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back) +{ + int dispose; + int first_frame; + int pi; + int pcount; + + // on first frame, any non-written pixels get the background colour (non-transparent) + first_frame = 0; + if (g->out == 0) { + if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header + g->out = (stbi_uc *) stbi__malloc(4 * g->w * g->h); + g->background = (stbi_uc *) stbi__malloc(4 * g->w * g->h); + g->history = (stbi_uc *) stbi__malloc(g->w * g->h); + if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory"); + + // image is treated as "tranparent" at the start - ie, nothing overwrites the current background; + // background colour is only used for pixels that are not rendered first frame, after that "background" + // color refers to teh color that was there the previous frame. + memset( g->out, 0x00, 4 * g->w * g->h ); + memset( g->background, 0x00, 4 * g->w * g->h ); // state of the background (starts transparent) + memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame + first_frame = 1; + } else { + // second frame - how do we dispoase of the previous one? + dispose = (g->eflags & 0x1C) >> 2; + pcount = g->w * g->h; + + if ((dispose == 3) && (two_back == 0)) { + dispose = 2; // if I don't have an image to revert back to, default to the old background + } + + if (dispose == 3) { // use previous graphic + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 ); + } + } + } else if (dispose == 2) { + // restore what was changed last frame to background before that frame; + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 ); + } + } + } else { + // This is a non-disposal case eithe way, so just + // leave the pixels as is, and they will become the new background + // 1: do not dispose + // 0: not specified. + } + + // background is what out is after the undoing of the previou frame; + memcpy( g->background, g->out, 4 * g->w * g->h ); + } + + // clear my history; + memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame + + for (;;) { + int tag = stbi__get8(s); + switch (tag) { + case 0x2C: /* Image Descriptor */ + { + stbi__int32 x, y, w, h; + stbi_uc *o; + + x = stbi__get16le(s); + y = stbi__get16le(s); + w = stbi__get16le(s); + h = stbi__get16le(s); + if (((x + w) > (g->w)) || ((y + h) > (g->h))) + return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); + + g->line_size = g->w * 4; + g->start_x = x * 4; + g->start_y = y * g->line_size; + g->max_x = g->start_x + w * 4; + g->max_y = g->start_y + h * g->line_size; + g->cur_x = g->start_x; + g->cur_y = g->start_y; + + g->lflags = stbi__get8(s); + + if (g->lflags & 0x40) { + g->step = 8 * g->line_size; // first interlaced spacing + g->parse = 3; + } else { + g->step = g->line_size; + g->parse = 0; + } + + if (g->lflags & 0x80) { + stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); + g->color_table = (stbi_uc *) g->lpal; + } else if (g->flags & 0x80) { + g->color_table = (stbi_uc *) g->pal; + } else + return stbi__errpuc("missing color table", "Corrupt GIF"); + + o = stbi__process_gif_raster(s, g); + if (o == NULL) return NULL; + + // if this was the first frame, + pcount = g->w * g->h; + if (first_frame && (g->bgindex > 0)) { + // if first frame, any pixel not drawn to gets the background color + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi] == 0) { + g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be; + memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 ); + } + } + } + + return o; + } + + case 0x21: // Comment Extension. + { + int len; + int ext = stbi__get8(s); + if (ext == 0xF9) { // Graphic Control Extension. + len = stbi__get8(s); + if (len == 4) { + g->eflags = stbi__get8(s); + g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths. + + // unset old transparent + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 255; + } + if (g->eflags & 0x01) { + g->transparent = stbi__get8(s); + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 0; + } + } else { + // don't need transparent + stbi__skip(s, 1); + g->transparent = -1; + } + } else { + stbi__skip(s, len); + break; + } + } + while ((len = stbi__get8(s)) != 0) { + stbi__skip(s, len); + } + break; + } + + case 0x3B: // gif stream termination code + return (stbi_uc *) s; // using '1' causes warning on some compilers + + default: + return stbi__errpuc("unknown code", "Corrupt GIF"); + } + } +} + +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + if (stbi__gif_test(s)) { + int layers = 0; + stbi_uc *u = 0; + stbi_uc *out = 0; + stbi_uc *two_back = 0; + stbi__gif g; + int stride; + memset(&g, 0, sizeof(g)); + if (delays) { + *delays = 0; + } + + do { + u = stbi__gif_load_next(s, &g, comp, req_comp, two_back); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + + if (u) { + *x = g.w; + *y = g.h; + ++layers; + stride = g.w * g.h * 4; + + if (out) { + out = (stbi_uc*) STBI_REALLOC( out, layers * stride ); + if (delays) { + *delays = (int*) STBI_REALLOC( *delays, sizeof(int) * layers ); + } + } else { + out = (stbi_uc*)stbi__malloc( layers * stride ); + if (delays) { + *delays = (int*) stbi__malloc( layers * sizeof(int) ); + } + } + memcpy( out + ((layers - 1) * stride), u, stride ); + if (layers >= 2) { + two_back = out - 2 * stride; + } + + if (delays) { + (*delays)[layers - 1U] = g.delay; + } + } + } while (u != 0); + + // free temp buffer; + STBI_FREE(g.out); + STBI_FREE(g.history); + STBI_FREE(g.background); + + // do the final conversion after loading everything; + if (req_comp && req_comp != 4) + out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h); + + *z = layers; + return out; + } else { + return stbi__errpuc("not GIF", "Image was not as a gif type."); + } +} + +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *u = 0; + stbi__gif g; + memset(&g, 0, sizeof(g)); + + u = stbi__gif_load_next(s, &g, comp, req_comp, 0); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + if (u) { + *x = g.w; + *y = g.h; + + // moved conversion to after successful load so that the same + // can be done for multiple frames. + if (req_comp && req_comp != 4) + u = stbi__convert_format(u, 4, req_comp, g.w, g.h); + } + + // free buffers needed for multiple frame loading; + STBI_FREE(g.history); + STBI_FREE(g.background); + + return u; +} + +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) +{ + return stbi__gif_info_raw(s,x,y,comp); +} +#endif + +// ************************************************************************************************* +// Radiance RGBE HDR loader +// originally by Nicolas Schulz +#ifndef STBI_NO_HDR +static int stbi__hdr_test_core(stbi__context *s, const char *signature) +{ + int i; + for (i=0; signature[i]; ++i) + if (stbi__get8(s) != signature[i]) + return 0; + stbi__rewind(s); + return 1; +} + +static int stbi__hdr_test(stbi__context* s) +{ + int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); + stbi__rewind(s); + if(!r) { + r = stbi__hdr_test_core(s, "#?RGBE\n"); + stbi__rewind(s); + } + return r; +} + +#define STBI__HDR_BUFLEN 1024 +static char *stbi__hdr_gettoken(stbi__context *z, char *buffer) +{ + int len=0; + char c = '\0'; + + c = (char) stbi__get8(z); + + while (!stbi__at_eof(z) && c != '\n') { + buffer[len++] = c; + if (len == STBI__HDR_BUFLEN-1) { + // flush to end of line + while (!stbi__at_eof(z) && stbi__get8(z) != '\n') + ; + break; + } + c = (char) stbi__get8(z); + } + + buffer[len] = 0; + return buffer; +} + +static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) +{ + if ( input[3] != 0 ) { + float f1; + // Exponent + f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8)); + if (req_comp <= 2) + output[0] = (input[0] + input[1] + input[2]) * f1 / 3; + else { + output[0] = input[0] * f1; + output[1] = input[1] * f1; + output[2] = input[2] * f1; + } + if (req_comp == 2) output[1] = 1; + if (req_comp == 4) output[3] = 1; + } else { + switch (req_comp) { + case 4: output[3] = 1; /* fallthrough */ + case 3: output[0] = output[1] = output[2] = 0; + break; + case 2: output[1] = 1; /* fallthrough */ + case 1: output[0] = 0; + break; + } + } +} + +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int width, height; + stbi_uc *scanline; + float *hdr_data; + int len; + unsigned char count, value; + int i, j, k, c1,c2, z; + const char *headerToken; + STBI_NOTUSED(ri); + + // Check identifier + headerToken = stbi__hdr_gettoken(s,buffer); + if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) + return stbi__errpf("not HDR", "Corrupt HDR image"); + + // Parse header + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); + + // Parse width and height + // can't use sscanf() if we're not using stdio! + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + height = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + width = (int) strtol(token, NULL, 10); + + *x = width; + *y = height; + + if (comp) *comp = 3; + if (req_comp == 0) req_comp = 3; + + if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) + return stbi__errpf("too large", "HDR image is too large"); + + // Read data + hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); + if (!hdr_data) + return stbi__errpf("outofmem", "Out of memory"); + + // Load image data + // image data is stored as some number of sca + if ( width < 8 || width >= 32768) { + // Read flat data + for (j=0; j < height; ++j) { + for (i=0; i < width; ++i) { + stbi_uc rgbe[4]; + main_decode_loop: + stbi__getn(s, rgbe, 4); + stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); + } + } + } else { + // Read RLE-encoded data + scanline = NULL; + + for (j = 0; j < height; ++j) { + c1 = stbi__get8(s); + c2 = stbi__get8(s); + len = stbi__get8(s); + if (c1 != 2 || c2 != 2 || (len & 0x80)) { + // not run-length encoded, so we have to actually use THIS data as a decoded + // pixel (note this can't be a valid pixel--one of RGB must be >= 128) + stbi_uc rgbe[4]; + rgbe[0] = (stbi_uc) c1; + rgbe[1] = (stbi_uc) c2; + rgbe[2] = (stbi_uc) len; + rgbe[3] = (stbi_uc) stbi__get8(s); + stbi__hdr_convert(hdr_data, rgbe, req_comp); + i = 1; + j = 0; + STBI_FREE(scanline); + goto main_decode_loop; // yes, this makes no sense + } + len <<= 8; + len |= stbi__get8(s); + if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } + if (scanline == NULL) { + scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0); + if (!scanline) { + STBI_FREE(hdr_data); + return stbi__errpf("outofmem", "Out of memory"); + } + } + + for (k = 0; k < 4; ++k) { + int nleft; + i = 0; + while ((nleft = width - i) > 0) { + count = stbi__get8(s); + if (count > 128) { + // Run + value = stbi__get8(s); + count -= 128; + if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = value; + } else { + // Dump + if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = stbi__get8(s); + } + } + } + for (i=0; i < width; ++i) + stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); + } + if (scanline) + STBI_FREE(scanline); + } + + return hdr_data; +} + +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int dummy; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (stbi__hdr_test(s) == 0) { + stbi__rewind( s ); + return 0; + } + + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) { + stbi__rewind( s ); + return 0; + } + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *y = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *x = (int) strtol(token, NULL, 10); + *comp = 3; + return 1; +} +#endif // STBI_NO_HDR + +#ifndef STBI_NO_BMP +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) +{ + void *p; + stbi__bmp_data info; + + info.all_a = 255; + p = stbi__bmp_parse_header(s, &info); + stbi__rewind( s ); + if (p == NULL) + return 0; + if (x) *x = s->img_x; + if (y) *y = s->img_y; + if (comp) *comp = info.ma ? 4 : 3; + return 1; +} +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) +{ + int channelCount, dummy, depth; + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + *y = stbi__get32be(s); + *x = stbi__get32be(s); + depth = stbi__get16be(s); + if (depth != 8 && depth != 16) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 3) { + stbi__rewind( s ); + return 0; + } + *comp = 4; + return 1; +} + +static int stbi__psd_is16(stbi__context *s) +{ + int channelCount, depth; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + (void) stbi__get32be(s); + (void) stbi__get32be(s); + depth = stbi__get16be(s); + if (depth != 16) { + stbi__rewind( s ); + return 0; + } + return 1; +} +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) +{ + int act_comp=0,num_packets=0,chained,dummy; + stbi__pic_packet packets[10]; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) { + stbi__rewind(s); + return 0; + } + + stbi__skip(s, 88); + + *x = stbi__get16be(s); + *y = stbi__get16be(s); + if (stbi__at_eof(s)) { + stbi__rewind( s); + return 0; + } + if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) { + stbi__rewind( s ); + return 0; + } + + stbi__skip(s, 8); + + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return 0; + + packet = &packets[num_packets++]; + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + act_comp |= packet->channel; + + if (stbi__at_eof(s)) { + stbi__rewind( s ); + return 0; + } + if (packet->size != 8) { + stbi__rewind( s ); + return 0; + } + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); + + return 1; +} +#endif + +// ************************************************************************************************* +// Portable Gray Map and Portable Pixel Map loader +// by Ken Miller +// +// PGM: http://netpbm.sourceforge.net/doc/pgm.html +// PPM: http://netpbm.sourceforge.net/doc/ppm.html +// +// Known limitations: +// Does not support comments in the header section +// Does not support ASCII image data (formats P2 and P3) +// Does not support 16-bit-per-channel + +#ifndef STBI_NO_PNM + +static int stbi__pnm_test(stbi__context *s) +{ + char p, t; + p = (char) stbi__get8(s); + t = (char) stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind( s ); + return 0; + } + return 1; +} + +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + STBI_NOTUSED(ri); + + if (!stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n)) + return 0; + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + + if (!stbi__mad3sizes_valid(s->img_n, s->img_x, s->img_y, 0)) + return stbi__errpuc("too large", "PNM too large"); + + out = (stbi_uc *) stbi__malloc_mad3(s->img_n, s->img_x, s->img_y, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + stbi__getn(s, out, s->img_n * s->img_x * s->img_y); + + if (req_comp && req_comp != s->img_n) { + out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + return out; +} + +static int stbi__pnm_isspace(char c) +{ + return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; +} + +static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) +{ + for (;;) { + while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) + *c = (char) stbi__get8(s); + + if (stbi__at_eof(s) || *c != '#') + break; + + while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' ) + *c = (char) stbi__get8(s); + } +} + +static int stbi__pnm_isdigit(char c) +{ + return c >= '0' && c <= '9'; +} + +static int stbi__pnm_getinteger(stbi__context *s, char *c) +{ + int value = 0; + + while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { + value = value*10 + (*c - '0'); + *c = (char) stbi__get8(s); + } + + return value; +} + +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) +{ + int maxv, dummy; + char c, p, t; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + stbi__rewind(s); + + // Get identifier + p = (char) stbi__get8(s); + t = (char) stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind(s); + return 0; + } + + *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm + + c = (char) stbi__get8(s); + stbi__pnm_skip_whitespace(s, &c); + + *x = stbi__pnm_getinteger(s, &c); // read width + stbi__pnm_skip_whitespace(s, &c); + + *y = stbi__pnm_getinteger(s, &c); // read height + stbi__pnm_skip_whitespace(s, &c); + + maxv = stbi__pnm_getinteger(s, &c); // read max value + + if (maxv > 255) + return stbi__err("max value > 255", "PPM image not 8-bit"); + else + return 1; +} +#endif + +static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) +{ + #ifndef STBI_NO_JPEG + if (stbi__jpeg_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PNG + if (stbi__png_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_GIF + if (stbi__gif_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_BMP + if (stbi__bmp_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PSD + if (stbi__psd_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PIC + if (stbi__pic_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PNM + if (stbi__pnm_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_HDR + if (stbi__hdr_info(s, x, y, comp)) return 1; + #endif + + // test tga last because it's a crappy test! + #ifndef STBI_NO_TGA + if (stbi__tga_info(s, x, y, comp)) + return 1; + #endif + return stbi__err("unknown image type", "Image not of any known type, or corrupt"); +} + +static int stbi__is_16_main(stbi__context *s) +{ + #ifndef STBI_NO_PNG + if (stbi__png_is16(s)) return 1; + #endif + + #ifndef STBI_NO_PSD + if (stbi__psd_is16(s)) return 1; + #endif + + return 0; +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_info_from_file(f, x, y, comp); + fclose(f); + return result; +} + +STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__info_main(&s,x,y,comp); + fseek(f,pos,SEEK_SET); + return r; +} + +STBIDEF int stbi_is_16_bit(char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_is_16_bit_from_file(f); + fclose(f); + return result; +} + +STBIDEF int stbi_is_16_bit_from_file(FILE *f) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__is_16_main(&s); + fseek(f,pos,SEEK_SET); + return r; +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__info_main(&s,x,y,comp); +} + +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__info_main(&s,x,y,comp); +} + +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__is_16_main(&s); +} + +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__is_16_main(&s); +} + +#endif // STB_IMAGE_IMPLEMENTATION + +/* + revision history: + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug + 1-bit BMP + *_is_16_bit api + avoid warnings + 2.16 (2017-07-23) all functions have 16-bit variants; + STBI_NO_STDIO works again; + compilation fixes; + fix rounding in unpremultiply; + optimize vertical flip; + disable raw_len validation; + documentation fixes + 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode; + warning fixes; disable run-time SSE detection on gcc; + uniform handling of optional "return" values; + thread-safe initialization of zlib tables + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) allocate large structures on the stack + remove white matting for transparent PSD + fix reported channel count for PNG & BMP + re-enable SSE2 in non-gcc 64-bit + support RGB-formatted JPEG + read 16-bit PNGs (only as 8-bit) + 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED + 2.09 (2016-01-16) allow comments in PNM files + 16-bit-per-pixel TGA (not bit-per-component) + info() for TGA could break due to .hdr handling + info() for BMP to shares code instead of sloppy parse + can use STBI_REALLOC_SIZED if allocator doesn't support realloc + code cleanup + 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA + 2.07 (2015-09-13) fix compiler warnings + partial animated GIF support + limited 16-bpc PSD support + #ifdef unused functions + bug with < 92 byte PIC,PNM,HDR,TGA + 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value + 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning + 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit + 2.03 (2015-04-12) extra corruption checking (mmozeiko) + stbi_set_flip_vertically_on_load (nguillemot) + fix NEON support; fix mingw support + 2.02 (2015-01-19) fix incorrect assert, fix warning + 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2 + 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG + 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) + progressive JPEG (stb) + PGM/PPM support (Ken Miller) + STBI_MALLOC,STBI_REALLOC,STBI_FREE + GIF bugfix -- seemingly never worked + STBI_NO_*, STBI_ONLY_* + 1.48 (2014-12-14) fix incorrectly-named assert() + 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb) + optimize PNG (ryg) + fix bug in interlaced PNG with user-specified channel count (stb) + 1.46 (2014-08-26) + fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG + 1.45 (2014-08-16) + fix MSVC-ARM internal compiler error by wrapping malloc + 1.44 (2014-08-07) + various warning fixes from Ronny Chevalier + 1.43 (2014-07-15) + fix MSVC-only compiler problem in code changed in 1.42 + 1.42 (2014-07-09) + don't define _CRT_SECURE_NO_WARNINGS (affects user code) + fixes to stbi__cleanup_jpeg path + added STBI_ASSERT to avoid requiring assert.h + 1.41 (2014-06-25) + fix search&replace from 1.36 that messed up comments/error messages + 1.40 (2014-06-22) + fix gcc struct-initialization warning + 1.39 (2014-06-15) + fix to TGA optimization when req_comp != number of components in TGA; + fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) + add support for BMP version 5 (more ignored fields) + 1.38 (2014-06-06) + suppress MSVC warnings on integer casts truncating values + fix accidental rename of 'skip' field of I/O + 1.37 (2014-06-04) + remove duplicate typedef + 1.36 (2014-06-03) + convert to header file single-file library + if de-iphone isn't set, load iphone images color-swapped instead of returning NULL + 1.35 (2014-05-27) + various warnings + fix broken STBI_SIMD path + fix bug where stbi_load_from_file no longer left file pointer in correct place + fix broken non-easy path for 32-bit BMP (possibly never used) + TGA optimization by Arseny Kapoulkine + 1.34 (unknown) + use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case + 1.33 (2011-07-14) + make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements + 1.32 (2011-07-13) + support for "info" function for all supported filetypes (SpartanJ) + 1.31 (2011-06-20) + a few more leak fixes, bug in PNG handling (SpartanJ) + 1.30 (2011-06-11) + added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) + removed deprecated format-specific test/load functions + removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway + error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) + fix inefficiency in decoding 32-bit BMP (David Woo) + 1.29 (2010-08-16) + various warning fixes from Aurelien Pocheville + 1.28 (2010-08-01) + fix bug in GIF palette transparency (SpartanJ) + 1.27 (2010-08-01) + cast-to-stbi_uc to fix warnings + 1.26 (2010-07-24) + fix bug in file buffering for PNG reported by SpartanJ + 1.25 (2010-07-17) + refix trans_data warning (Won Chun) + 1.24 (2010-07-12) + perf improvements reading from files on platforms with lock-heavy fgetc() + minor perf improvements for jpeg + deprecated type-specific functions so we'll get feedback if they're needed + attempt to fix trans_data warning (Won Chun) + 1.23 fixed bug in iPhone support + 1.22 (2010-07-10) + removed image *writing* support + stbi_info support from Jetro Lauha + GIF support from Jean-Marc Lienher + iPhone PNG-extensions from James Brown + warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) + 1.21 fix use of 'stbi_uc' in header (reported by jon blow) + 1.20 added support for Softimage PIC, by Tom Seddon + 1.19 bug in interlaced PNG corruption check (found by ryg) + 1.18 (2008-08-02) + fix a threading bug (local mutable static) + 1.17 support interlaced PNG + 1.16 major bugfix - stbi__convert_format converted one too many pixels + 1.15 initialize some fields for thread safety + 1.14 fix threadsafe conversion bug + header-file-only version (#define STBI_HEADER_FILE_ONLY before including) + 1.13 threadsafe + 1.12 const qualifiers in the API + 1.11 Support installable IDCT, colorspace conversion routines + 1.10 Fixes for 64-bit (don't use "unsigned long") + optimized upsampling by Fabian "ryg" Giesen + 1.09 Fix format-conversion for PSD code (bad global variables!) + 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz + 1.07 attempt to fix C++ warning/errors again + 1.06 attempt to fix C++ warning/errors again + 1.05 fix TGA loading to return correct *comp and use good luminance calc + 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free + 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR + 1.02 support for (subset of) HDR files, float interface for preferred access to them + 1.01 fix bug: possible bug in handling right-side up bmps... not sure + fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all + 1.00 interface to zlib that skips zlib header + 0.99 correct handling of alpha in palette + 0.98 TGA loader by lonesock; dynamically add loaders (untested) + 0.97 jpeg errors on too large a file; also catch another malloc failure + 0.96 fix detection of invalid v value - particleman@mollyrocket forum + 0.95 during header scan, seek to markers in case of padding + 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same + 0.93 handle jpegtran output; verbose errors + 0.92 read 4,8,16,24,32-bit BMP files of several formats + 0.91 output 24-bit Windows 3.0 BMP files + 0.90 fix a few more warnings; bump version number to approach 1.0 + 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd + 0.60 fix compiling as c++ + 0.59 fix warnings: merge Dave Moore's -Wall fixes + 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian + 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available + 0.56 fix bug: zlib uncompressed mode len vs. nlen + 0.55 fix bug: restart_interval not initialized to 0 + 0.54 allow NULL for 'int *comp' + 0.53 fix bug in png 3->4; speedup png decoding + 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments + 0.51 obey req_comp requests, 1-component jpegs return as 1-component, + on 'test' only check type, not whether we support this variant + 0.50 (2006-11-19) + first released version +*/ + + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +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. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +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 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. +------------------------------------------------------------------------------ +*/ \ No newline at end of file diff --git a/third_party/libassimp/contrib/zip/.gitignore b/third_party/libassimp/contrib/zip/.gitignore deleted file mode 100644 index 4f9972c567..0000000000 --- a/third_party/libassimp/contrib/zip/.gitignore +++ /dev/null @@ -1,38 +0,0 @@ -/build/ -/test/build/ -/xcodeproj/ - -# Object files -*.o -*.ko -*.obj -*.elf - -# Precompiled Headers -*.gch -*.pch - -# Libraries -*.lib -*.a -*.la -*.lo - -# Shared objects (inc. Windows DLLs) -*.dll -*.so -*.so.* -*.dylib -*.suo - -# Executables -*.exe -*.out -*.app -*.i*86 -*.x86_64 -*.hex - -# Temporary -*.swp -.DS_Store diff --git a/third_party/libassimp/contrib/zip/.travis.sh b/third_party/libassimp/contrib/zip/.travis.sh new file mode 100755 index 0000000000..22974b1ff1 --- /dev/null +++ b/third_party/libassimp/contrib/zip/.travis.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# +# Build script for travis-ci.org builds. +# +if [ $ANALYZE = "true" ] && [ "$CC" = "clang" ]; then + # scan-build -h + scan-build cmake -G "Unix Makefiles" + scan-build -enable-checker security.FloatLoopCounter \ + -enable-checker security.insecureAPI.UncheckedReturn \ + --status-bugs -v \ + make -j 8 \ + make -j 8 test +else + cmake -DCMAKE_BUILD_TYPE=Debug -DSANITIZE_ADDRESS=On -DCMAKE_INSTALL_PREFIX=_install + make -j 8 + make install + ASAN_OPTIONS=detect_leaks=0 LSAN_OPTIONS=verbosity=1:log_threads=1 ctest -V +fi \ No newline at end of file diff --git a/third_party/libassimp/contrib/zip/.travis.yml b/third_party/libassimp/contrib/zip/.travis.yml index d8ccb728d4..86bac1ccaa 100644 --- a/third_party/libassimp/contrib/zip/.travis.yml +++ b/third_party/libassimp/contrib/zip/.travis.yml @@ -1,10 +1,22 @@ language: c +addons: + apt: + packages: &1 + - lcov # Compiler selection compiler: - clang - gcc +env: + - ANALYZE=false + - ANALYZE=true # Build steps script: - - mkdir build - - cd build - - cmake -DCMAKE_BUILD_TYPE=Debug .. && make && make test + - ./.travis.sh +after_success: + # Creating report + - cmake -DENABLE_COVERAGE=ON + - make + - make test + # Uploading report to CodeCov + - bash <(curl -s https://codecov.io/bash) \ No newline at end of file diff --git a/third_party/libassimp/contrib/zip/CMakeLists.txt b/third_party/libassimp/contrib/zip/CMakeLists.txt index 450ef3a987..b46dbb1db0 100644 --- a/third_party/libassimp/contrib/zip/CMakeLists.txt +++ b/third_party/libassimp/contrib/zip/CMakeLists.txt @@ -1,18 +1,47 @@ cmake_minimum_required(VERSION 2.8) project(zip) +enable_language(C) +set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake" ${CMAKE_MODULE_PATH}) if (MSVC) - # Use secure functions by defaualt and suppress warnings about "deprecated" functions - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES=1") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT=1") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /D _CRT_NONSTDC_NO_WARNINGS=1 /D _CRT_SECURE_NO_WARNINGS=1") + # Use secure functions by defaualt and suppress warnings about "deprecated" functions + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES=1") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT=1") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /D _CRT_NONSTDC_NO_WARNINGS=1 /D _CRT_SECURE_NO_WARNINGS=1") +elseif ("${CMAKE_C_COMPILER_ID}" STREQUAL "GNU" OR + "${CMAKE_C_COMPILER_ID}" STREQUAL "Clang" OR + "${CMAKE_C_COMPILER_ID}" STREQUAL "AppleClang") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -Wall -Wextra -Werror -pedantic") endif (MSVC) # zip set(SRC src/miniz.h src/zip.h src/zip.c) -add_library(${CMAKE_PROJECT_NAME} ${SRC}) +add_library(${PROJECT_NAME} ${SRC}) +target_include_directories(${PROJECT_NAME} INTERFACE src) # test -enable_testing() -add_subdirectory(test) +if (NOT CMAKE_DISABLE_TESTING) + enable_testing() + add_subdirectory(test) + find_package(Sanitizers) + add_sanitizers(${PROJECT_NAME} test.exe) + add_sanitizers(${PROJECT_NAME} test_miniz.exe) +endif() +install(TARGETS ${PROJECT_NAME} + RUNTIME DESTINATION bin + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + COMPONENT library) +install(FILES ${PROJECT_SOURCE_DIR}/src/zip.h DESTINATION include) + +# uninstall target (https://gitlab.kitware.com/cmake/community/wikis/FAQ#can-i-do-make-uninstall-with-cmake) +if(NOT TARGET uninstall) + configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/cmake/cmake_uninstall.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/cmake/cmake_uninstall.cmake" + IMMEDIATE @ONLY) + + add_custom_target(uninstall + COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake/cmake_uninstall.cmake) +endif() diff --git a/third_party/libassimp/contrib/zip/README.md b/third_party/libassimp/contrib/zip/README.md index 24de5e61a2..d5fb8cd203 100644 --- a/third_party/libassimp/contrib/zip/README.md +++ b/third_party/libassimp/contrib/zip/README.md @@ -1,12 +1,11 @@ ### A portable (OSX/Linux/Windows), simple zip library written in C This is done by hacking awesome [miniz](https://code.google.com/p/miniz) library and layering functions on top of the miniz v1.15 API. -[![Windows][win-badge]][win-link] [![OS X][osx-linux-badge]][osx-linux-link] +[![Windows](https://ci.appveyor.com/api/projects/status/bph8dr3jacgmjv32/branch/master?svg=true&label=windows)](https://ci.appveyor.com/project/kuba--/zip) +[![Linux](https://travis-ci.org/kuba--/zip.svg?branch=master&label=linux%2fosx)](https://travis-ci.org/kuba--/zip) +[![Version](https://badge.fury.io/gh/kuba--%2Fzip.svg)](https://github.com/kuba--/zip/releases) +[![Codecov](https://codecov.io/gh/kuba--/zip/branch/master/graph/badge.svg)](https://codecov.io/gh/kuba--/zip) -[win-badge]: https://img.shields.io/appveyor/ci/kuba--/zip/master.svg?label=windows "AppVeyor build status" -[win-link]: https://ci.appveyor.com/project/kuba--/zip "AppVeyor build status" -[osx-linux-badge]: https://img.shields.io/travis/kuba--/zip/master.svg?label=linux/osx "Travis CI build status" -[osx-linux-link]: https://travis-ci.org/kuba--/zip "Travis CI build status" # The Idea @@ -23,117 +22,288 @@ It was the reason, why I decided to write zip module on top of the miniz. It req * Create a new zip archive with default compression level. ```c - struct zip_t *zip = zip_open("foo.zip", ZIP_DEFAULT_COMPRESSION_LEVEL, 'w'); +struct zip_t *zip = zip_open("foo.zip", ZIP_DEFAULT_COMPRESSION_LEVEL, 'w'); +{ + zip_entry_open(zip, "foo-1.txt"); { - zip_entry_open(zip, "foo-1.txt"); - { - char *buf = "Some data here..."; - zip_entry_write(zip, buf, strlen(buf)); - } - zip_entry_close(zip); - - zip_entry_open(zip, "foo-2.txt"); - { - // merge 3 files into one entry and compress them on-the-fly. - zip_entry_fwrite(zip, "foo-2.1.txt"); - zip_entry_fwrite(zip, "foo-2.2.txt"); - zip_entry_fwrite(zip, "foo-2.3.txt"); - } - zip_entry_close(zip); + const char *buf = "Some data here...\0"; + zip_entry_write(zip, buf, strlen(buf)); } - zip_close(zip); + zip_entry_close(zip); + + zip_entry_open(zip, "foo-2.txt"); + { + // merge 3 files into one entry and compress them on-the-fly. + zip_entry_fwrite(zip, "foo-2.1.txt"); + zip_entry_fwrite(zip, "foo-2.2.txt"); + zip_entry_fwrite(zip, "foo-2.3.txt"); + } + zip_entry_close(zip); +} +zip_close(zip); ``` * Append to the existing zip archive. ```c - struct zip_t *zip = zip_open("foo.zip", ZIP_DEFAULT_COMPRESSION_LEVEL, 'a'); +struct zip_t *zip = zip_open("foo.zip", ZIP_DEFAULT_COMPRESSION_LEVEL, 'a'); +{ + zip_entry_open(zip, "foo-3.txt"); { - zip_entry_open(zip, "foo-3.txt"); - { - char *buf = "Append some data here..."; - zip_entry_write(zip, buf, strlen(buf)); - } - zip_entry_close(zip); + const char *buf = "Append some data here...\0"; + zip_entry_write(zip, buf, strlen(buf)); } - zip_close(zip); + zip_entry_close(zip); +} +zip_close(zip); ``` * Extract a zip archive into a folder. ```c - int on_extract_entry(const char *filename, void *arg) { - static int i = 0; - int n = *(int *)arg; - printf("Extracted: %s (%d of %d)\n", filename, ++i, n); +int on_extract_entry(const char *filename, void *arg) { + static int i = 0; + int n = *(int *)arg; + printf("Extracted: %s (%d of %d)\n", filename, ++i, n); - return 0; - } + return 0; +} - int arg = 2; - zip_extract("foo.zip", "/tmp", on_extract_entry, &arg); +int arg = 2; +zip_extract("foo.zip", "/tmp", on_extract_entry, &arg); ``` -* Extract a zip entry into memory. +* Extract a zip entry into memory. ```c - void *buf = NULL; - size_t bufsize; +void *buf = NULL; +size_t bufsize; - struct zip_t *zip = zip_open("foo.zip", 0, 'r'); +struct zip_t *zip = zip_open("foo.zip", 0, 'r'); +{ + zip_entry_open(zip, "foo-1.txt"); { - zip_entry_open(zip, "foo-1.txt"); - { - zip_entry_read(zip, &buf, &bufsize); - } - zip_entry_close(zip); + zip_entry_read(zip, &buf, &bufsize); } - zip_close(zip); + zip_entry_close(zip); +} +zip_close(zip); - free(buf); +free(buf); ``` -* Extract a zip entry into memory using callback. +* Extract a zip entry into memory (no internal allocation). ```c - struct buffer_t { - char *data; - size_t size; - }; +unsigned char *buf; +size_t bufsize; - static size_t on_extract(void *arg, unsigned long long offset, const void *data, size_t size) { - struct buffer_t *buf = (struct buffer_t *)arg; - buf->data = realloc(buf->data, buf->size + size + 1); - assert(NULL != buf->data); - - memcpy(&(buf->data[buf->size]), data, size); - buf->size += size; - buf->data[buf->size] = 0; - - return size; - } - - struct buffer_t buf = {0}; - struct zip_t *zip = zip_open("foo.zip", 0, 'r'); +struct zip_t *zip = zip_open("foo.zip", 0, 'r'); +{ + zip_entry_open(zip, "foo-1.txt"); { - zip_entry_open(zip, "foo-1.txt"); - { - zip_entry_extract(zip, on_extract, &buf); - } - zip_entry_close(zip); - } - zip_close(zip); + bufsize = zip_entry_size(zip); + buf = calloc(sizeof(unsigned char), bufsize); - free(buf.data); + zip_entry_noallocread(zip, (void *)buf, bufsize); + } + zip_entry_close(zip); +} +zip_close(zip); + +free(buf); ``` - -* Extract a zip entry into a file. +* Extract a zip entry into memory using callback. ```c - struct zip_t *zip = zip_open("foo.zip", 0, 'r'); +struct buffer_t { + char *data; + size_t size; +}; + +static size_t on_extract(void *arg, unsigned long long offset, const void *data, size_t size) { + struct buffer_t *buf = (struct buffer_t *)arg; + buf->data = realloc(buf->data, buf->size + size + 1); + assert(NULL != buf->data); + + memcpy(&(buf->data[buf->size]), data, size); + buf->size += size; + buf->data[buf->size] = 0; + + return size; +} + +struct buffer_t buf = {0}; +struct zip_t *zip = zip_open("foo.zip", 0, 'r'); +{ + zip_entry_open(zip, "foo-1.txt"); { - zip_entry_open(zip, "foo-2.txt"); - { - zip_entry_fread(zip, "foo-2.txt"); - } - zip_entry_close(zip); + zip_entry_extract(zip, on_extract, &buf); } - zip_close(zip); + zip_entry_close(zip); +} +zip_close(zip); + +free(buf.data); +``` + + +* Extract a zip entry into a file. +```c +struct zip_t *zip = zip_open("foo.zip", 0, 'r'); +{ + zip_entry_open(zip, "foo-2.txt"); + { + zip_entry_fread(zip, "foo-2.txt"); + } + zip_entry_close(zip); +} +zip_close(zip); +``` + +* List of all zip entries +```c +struct zip_t *zip = zip_open("foo.zip", 0, 'r'); +int i, n = zip_total_entries(zip); +for (i = 0; i < n; ++i) { + zip_entry_openbyindex(zip, i); + { + const char *name = zip_entry_name(zip); + int isdir = zip_entry_isdir(zip); + unsigned long long size = zip_entry_size(zip); + unsigned int crc32 = zip_entry_crc32(zip); + } + zip_entry_close(zip); +} +zip_close(zip); +``` + +## Bindings +Compile zip library as a dynamic library. +```shell +$ mkdir build +$ cd build +$ cmake -DBUILD_SHARED_LIBS=true .. +$ make +``` + +### Go (cgo) +```go +package main + +/* +#cgo CFLAGS: -I../src +#cgo LDFLAGS: -L. -lzip +#include +*/ +import "C" +import "unsafe" + +func main() { + path := C.CString("/tmp/go.zip") + zip := C.zip_open(path, 6, 'w') + + entryname := C.CString("test") + C.zip_entry_open(zip, entryname) + + content := "test content" + buf := unsafe.Pointer(C.CString(content)) + bufsize := C.size_t(len(content)) + C.zip_entry_write(zip, buf, bufsize) + + C.zip_entry_close(zip) + + C.zip_close(zip) +} +``` + +### Ruby (ffi) +Install _ffi_ gem. +```shell +$ gem install ffi +``` + +Bind in your module. +```ruby +require 'ffi' + +module Zip + extend FFI::Library + ffi_lib "./libzip.#{::FFI::Platform::LIBSUFFIX}" + + attach_function :zip_open, [:string, :int, :char], :pointer + attach_function :zip_close, [:pointer], :void + + attach_function :zip_entry_open, [:pointer, :string], :int + attach_function :zip_entry_close, [:pointer], :void + attach_function :zip_entry_write, [:pointer, :string, :int], :int +end + +ptr = Zip.zip_open("/tmp/ruby.zip", 6, "w".bytes()[0]) + +status = Zip.zip_entry_open(ptr, "test") + +content = "test content" +status = Zip.zip_entry_write(ptr, content, content.size()) + +Zip.zip_entry_close(ptr) +Zip.zip_close(ptr) +``` + +### Python (cffi) +Install _cffi_ package +```shell +$ pip install cffi +``` + +Bind in your package. +```python +import ctypes.util +from cffi import FFI + +ffi = FFI() +ffi.cdef(""" + struct zip_t *zip_open(const char *zipname, int level, char mode); + void zip_close(struct zip_t *zip); + + int zip_entry_open(struct zip_t *zip, const char *entryname); + int zip_entry_close(struct zip_t *zip); + int zip_entry_write(struct zip_t *zip, const void *buf, size_t bufsize); +""") + +Zip = ffi.dlopen(ctypes.util.find_library("zip")) + +ptr = Zip.zip_open("/tmp/python.zip", 6, 'w') + +status = Zip.zip_entry_open(ptr, "test") + +content = "test content" +status = Zip.zip_entry_write(ptr, content, len(content)) + +Zip.zip_entry_close(ptr) +Zip.zip_close(ptr) +``` + +### Ring +The language comes with RingZip based on this library +```ring +load "ziplib.ring" + +new Zip { + setFileName("myfile.zip") + open("w") + newEntry() { + open("test.c") + writefile("test.c") + close() + } + close() +} +``` + +# Contribution Rules/Coding Standards +No need to throw away your coding style, just do your best to follow default clang-format style. +Apply `clang-format` to the source files before commit: +```sh +for file in $(git ls-files | \grep -E '\.(c|h)$' | \grep -v -- '#') +do + clang-format -i $file +done ``` diff --git a/third_party/libassimp/contrib/zip/appveyor.yml b/third_party/libassimp/contrib/zip/appveyor.yml deleted file mode 100644 index 297cad8b0f..0000000000 --- a/third_party/libassimp/contrib/zip/appveyor.yml +++ /dev/null @@ -1,14 +0,0 @@ -version: 1.0.{build} -build_script: -- cmd: >- - cd c:\projects\zip - - mkdir build - - cd build - - cmake -G"Visual Studio 14" -DCMAKE_BUILD_TYPE=Debug .. - - cmake --build . --config %CMAKE_BUILD_TYPE% - - ctest --verbose -C "Debug" diff --git a/third_party/libassimp/contrib/zip/cmake/asan-wrapper b/third_party/libassimp/contrib/zip/cmake/asan-wrapper new file mode 100755 index 0000000000..5d54103372 --- /dev/null +++ b/third_party/libassimp/contrib/zip/cmake/asan-wrapper @@ -0,0 +1,55 @@ +#!/bin/sh + +# The MIT License (MIT) +# +# Copyright (c) +# 2013 Matthew Arsenault +# 2015-2016 RWTH Aachen University, Federal Republic of Germany +# +# 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. + +# This script is a wrapper for AddressSanitizer. In some special cases you need +# to preload AddressSanitizer to avoid error messages - e.g. if you're +# preloading another library to your application. At the moment this script will +# only do something, if we're running on a Linux platform. OSX might not be +# affected. + + +# Exit immediately, if platform is not Linux. +if [ "$(uname)" != "Linux" ] +then + exec $@ +fi + + +# Get the used libasan of the application ($1). If a libasan was found, it will +# be prepended to LD_PRELOAD. +libasan=$(ldd $1 | grep libasan | sed "s/^[[:space:]]//" | cut -d' ' -f1) +if [ -n "$libasan" ] +then + if [ -n "$LD_PRELOAD" ] + then + export LD_PRELOAD="$libasan:$LD_PRELOAD" + else + export LD_PRELOAD="$libasan" + fi +fi + +# Execute the application. +exec $@ diff --git a/third_party/libassimp/contrib/zip/cmake/cmake_uninstall.cmake.in b/third_party/libassimp/contrib/zip/cmake/cmake_uninstall.cmake.in new file mode 100644 index 0000000000..86ea34d8f4 --- /dev/null +++ b/third_party/libassimp/contrib/zip/cmake/cmake_uninstall.cmake.in @@ -0,0 +1,23 @@ +# copied from https://gitlab.kitware.com/cmake/community/wikis/FAQ#can-i-do-make-uninstall-with-cmake +if(NOT EXISTS "@CMAKE_BINARY_DIR@/install_manifest.txt") + message(FATAL_ERROR "Cannot find install manifest: @CMAKE_BINARY_DIR@/install_manifest.txt") +endif(NOT EXISTS "@CMAKE_BINARY_DIR@/install_manifest.txt") + +file(READ "@CMAKE_BINARY_DIR@/install_manifest.txt" files) +string(REGEX REPLACE "\n" ";" files "${files}") +foreach(file ${files}) + message(STATUS "Uninstalling $ENV{DESTDIR}${file}") + if(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") + exec_program( + "@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\"" + OUTPUT_VARIABLE rm_out + RETURN_VALUE rm_retval + ) + if(NOT "${rm_retval}" STREQUAL 0) + message(FATAL_ERROR "Problem when removing $ENV{DESTDIR}${file}") + endif(NOT "${rm_retval}" STREQUAL 0) + else(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") + message(STATUS "File $ENV{DESTDIR}${file} does not exist.") + endif(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") +endforeach(file) + diff --git a/third_party/libassimp/contrib/zip/src/miniz.h b/third_party/libassimp/contrib/zip/src/miniz.h index 935f7de2e8..2c27a94d8d 100644 --- a/third_party/libassimp/contrib/zip/src/miniz.h +++ b/third_party/libassimp/contrib/zip/src/miniz.h @@ -1,160 +1,221 @@ /* - miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing - See "unlicense" statement at the end of this file. - Rich Geldreich , last updated Oct. 13, 2013 - Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt + miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP + reading/writing/appending, PNG writing See "unlicense" statement at the end + of this file. Rich Geldreich , last updated Oct. 13, + 2013 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: + http://www.ietf.org/rfc/rfc1951.txt - Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define - MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). + Most API's defined in miniz.c are optional. For example, to disable the + archive related functions just define MINIZ_NO_ARCHIVE_APIS, or to get rid of + all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). * Change History - 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!): - - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks kahmyong.moon@hp.com) which could cause locate files to not find files. This bug - would only have occured in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place() - (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag). - - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size - - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries. - Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice). - - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes + 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major + release with Zip64 support (almost there!): + - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug + (thanks kahmyong.moon@hp.com) which could cause locate files to not find + files. This bug would only have occured in earlier versions if you explicitly + used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or + mz_zip_add_mem_to_archive_file_in_place() (which used this flag). If you + can't switch to v1.15 but want to fix this bug, just remove the uses of this + flag from both helper funcs (and of course don't use the flag). + - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when + pUser_read_buf is not NULL and compressed size is > uncompressed size + - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract + compressed data from directory entries, to account for weird zipfiles which + contain zero-size compressed data on dir entries. Hopefully this fix won't + cause any issues on weird zip archives, because it assumes the low 16-bits of + zip external attributes are DOS attributes (which I believe they always are + in practice). + - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the + internal attributes, just the filename and external attributes - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed - - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6. + - Added cmake support for Linux builds which builds all the examples, + tested with clang v3.3 and gcc v4.6. - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti - Merged MZ_FORCEINLINE fix from hdeanclark - Fix include before config #ifdef, thanks emil.brink - - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can - set it to 1 for real-time compression). + - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping + (super useful for OpenGL apps), and explicit control over the compression + level (so you can set it to 1 for real-time compression). - Merged in some compiler fixes from paulharris's github repro. - - Retested this build under Windows (VS 2010, including static analysis), tcc 0.9.26, gcc v4.6 and clang v3.3. - - Added example6.c, which dumps an image of the mandelbrot set to a PNG file. - - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more. - - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled -  - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch - 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include (thanks fermtect). - 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit. - - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files. + - Retested this build under Windows (VS 2010, including static analysis), + tcc 0.9.26, gcc v4.6 and clang v3.3. + - Added example6.c, which dumps an image of the mandelbrot set to a PNG + file. + - Modified example2 to help test the + MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more. + - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix + possible src file fclose() leak if alignment bytes+local header file write + faiiled + - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the + wrong central dir header offset, appears harmless in this release, but it + became a problem in the zip64 branch 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 + compiler fixes: added MZ_FORCEINLINE, #include (thanks fermtect). + 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix + mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit. + - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and + re-ran a randomized regression test on ~500k files. - Eliminated a bunch of warnings when compiling with GCC 32-bit/64. - - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly - "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning). - - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64. - - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test. - - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives. - - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.) - - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself). - 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. - level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson for the feedback/bug report. - 5/28/11 v1.11 - Added statement from unlicense.org - 5/27/11 v1.10 - Substantial compressor optimizations: - - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a - - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). - - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. - - Refactored the compression code for better readability and maintainability. - - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large - drop in throughput on some files). - 5/15/11 v1.09 - Initial stable release. + - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze + (static analysis) option and fixed all warnings (except for the silly "Use of + the comma-operator in a tested expression.." analysis warning, which I + purposely use to work around a MSVC compiler warning). + - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and + tested Linux executables. The codeblocks workspace is compatible with + Linux+Win32/x64. + - Added miniz_tester solution/project, which is a useful little app + derived from LZHAM's tester app that I use as part of the regression test. + - Ran miniz.c and tinfl.c through another series of regression testing on + ~500,000 files and archives. + - Modified example5.c so it purposely disables a bunch of high-level + functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the + MINIZ_NO_STDIO bug report.) + - Fix ftell() usage in examples so they exit with an error on files which + are too large (a limitation of the examples, not miniz itself). 4/12/12 v1.12 + - More comments, added low-level example5.c, fixed a couple minor + level_and_flags issues in the archive API's. level_and_flags can now be set + to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson + for the feedback/bug report. 5/28/11 v1.11 - Added statement from + unlicense.org 5/27/11 v1.10 - Substantial compressor optimizations: + - Level 1 is now ~4x faster than before. The L1 compressor's throughput + now varies between 70-110MB/sec. on a + - Core i7 (actual throughput varies depending on the type of data, and x64 + vs. x86). + - Improved baseline L2-L9 compression perf. Also, greatly improved + compression perf. issues on some file types. + - Refactored the compression code for better readability and + maintainability. + - Added level 10 compression level (L10 has slightly better ratio than + level 9, but could have a potentially large drop in throughput on some + files). 5/15/11 v1.09 - Initial stable release. * Low-level Deflate/Inflate implementation notes: - Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or - greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses - approximately as well as zlib. + Compression: Use the "tdefl" API's. The compressor supports raw, static, + and dynamic blocks, lazy or greedy parsing, match length filtering, RLE-only, + and Huffman-only streams. It performs and compresses approximately as well as + zlib. - Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function - coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory - block large enough to hold the entire file. + Decompression: Use the "tinfl" API's. The entire decompressor is + implemented as a single function coroutine: see tinfl_decompress(). It + supports decompression into a 32KB (or larger power of 2) wrapping buffer, or + into a memory block large enough to hold the entire file. - The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. + The low-level tdefl/tinfl API's do not make any use of dynamic memory + allocation. * zlib-style API notes: - miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in - zlib replacement in many apps: + miniz.c implements a fairly large subset of zlib. There's enough + functionality present for it to be a drop-in zlib replacement in many apps: The z_stream struct, optional memory allocation callbacks deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound inflateInit/inflateInit2/inflate/inflateEnd compress, compress2, compressBound, uncompress - CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. - Supports raw deflate streams or standard zlib streams with adler-32 checking. + CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly + routines. Supports raw deflate streams or standard zlib streams with adler-32 + checking. Limitations: - The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. - I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but - there are no guarantees that miniz.c pulls this off perfectly. + The callback API's are not implemented yet. No support for gzip headers or + zlib static dictionaries. I've tried to closely emulate zlib's various + flavors of stream flushing and return status codes, but there are no + guarantees that miniz.c pulls this off perfectly. - * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by - Alex Evans. Supports 1-4 bytes/pixel images. + * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, + originally written by Alex Evans. Supports 1-4 bytes/pixel images. * ZIP archive API notes: - The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to - get the job done with minimal fuss. There are simple API's to retrieve file information, read files from - existing archives, create new archives, append new files to existing archives, or clone archive data from - one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), - or you can specify custom file read/write callbacks. + The ZIP archive API's where designed with simplicity and efficiency in + mind, with just enough abstraction to get the job done with minimal fuss. + There are simple API's to retrieve file information, read files from existing + archives, create new archives, append new files to existing archives, or + clone archive data from one archive to another. It supports archives located + in memory or the heap, on disk (using stdio.h), or you can specify custom + file read/write callbacks. - - Archive reading: Just call this function to read a single file from a disk archive: + - Archive reading: Just call this function to read a single file from a + disk archive: - void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, - size_t *pSize, mz_uint zip_flags); + void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const + char *pArchive_name, size_t *pSize, mz_uint zip_flags); - For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central - directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. + For more complex cases, use the "mz_zip_reader" functions. Upon opening an + archive, the entire central directory is located and read as-is into memory, + and subsequent file access only occurs when reading individual files. - - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: + - Archives file scanning: The simple way is to use this function to scan a + loaded archive for a specific file: - int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, + const char *pComment, mz_uint flags); - The locate operation can optionally check file comments too, which (as one example) can be used to identify - multiple versions of the same file in an archive. This function uses a simple linear search through the central + The locate operation can optionally check file comments too, which (as one + example) can be used to identify multiple versions of the same file in an + archive. This function uses a simple linear search through the central directory, so it's not very fast. - Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and - retrieve detailed info on each file by calling mz_zip_reader_file_stat(). + Alternately, you can iterate through all the files in an archive (using + mz_zip_reader_get_num_files()) and retrieve detailed info on each file by + calling mz_zip_reader_file_stat(). - - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data - to disk and builds an exact image of the central directory in memory. The central directory image is written - all at once at the end of the archive file when the archive is finalized. + - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer + immediately writes compressed file data to disk and builds an exact image of + the central directory in memory. The central directory image is written all + at once at the end of the archive file when the archive is finalized. - The archive writer can optionally align each file's local header and file data to any power of 2 alignment, - which can be useful when the archive will be read from optical media. Also, the writer supports placing - arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still - readable by any ZIP tool. + The archive writer can optionally align each file's local header and file + data to any power of 2 alignment, which can be useful when the archive will + be read from optical media. Also, the writer supports placing arbitrary data + blobs at the very beginning of ZIP archives. Archives written using either + feature are still readable by any ZIP tool. - - Archive appending: The simple way to add a single file to an archive is to call this function: + - Archive appending: The simple way to add a single file to an archive is + to call this function: - mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, - const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, + const char *pArchive_name, const void *pBuf, size_t buf_size, const void + *pComment, mz_uint16 comment_size, mz_uint level_and_flags); - The archive will be created if it doesn't already exist, otherwise it'll be appended to. - Note the appending is done in-place and is not an atomic operation, so if something goes wrong - during the operation it's possible the archive could be left without a central directory (although the local - file headers and file data will be fine, so the archive will be recoverable). + The archive will be created if it doesn't already exist, otherwise it'll be + appended to. Note the appending is done in-place and is not an atomic + operation, so if something goes wrong during the operation it's possible the + archive could be left without a central directory (although the local file + headers and file data will be fine, so the archive will be recoverable). For more complex archive modification scenarios: - 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to - preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the - compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and - you're done. This is safe but requires a bunch of temporary disk space or heap memory. + 1. The safest way is to use a mz_zip_reader to read the existing archive, + cloning only those bits you want to preserve into a new archive using using + the mz_zip_writer_add_from_zip_reader() function (which compiles the + compressed file data as-is). When you're done, delete the old archive and + rename the newly written archive, and you're done. This is safe but requires + a bunch of temporary disk space or heap memory. - 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), - append new files as needed, then finalize the archive which will write an updated central directory to the - original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a - possibility that the archive's central directory could be lost with this method if anything goes wrong, though. + 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using + mz_zip_writer_init_from_reader(), append new files as needed, then finalize + the archive which will write an updated central directory to the original + archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() + does.) There's a possibility that the archive's central directory could be + lost with this method if anything goes wrong, though. - ZIP archive support limitations: - No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. - Requires streams capable of seeking. + No zip64 or spanning support. Extraction functions can only handle + unencrypted, stored or deflated files. Requires streams capable of seeking. - * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the - below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. + * This is a header file library, like stb_image.c. To get only a header file, + either cut and paste the below header, or create miniz.h, #define + MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. - * Important: For best perf. be sure to customize the below macros for your target platform: - #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 - #define MINIZ_LITTLE_ENDIAN 1 - #define MINIZ_HAS_64BIT_REGISTERS 1 + * Important: For best perf. be sure to customize the below macros for your + target platform: #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define + MINIZ_LITTLE_ENDIAN 1 #define MINIZ_HAS_64BIT_REGISTERS 1 - * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz - uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files - (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). + * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before + including miniz.c to ensure miniz uses the 64-bit variants: fopen64(), + stat64(), etc. Otherwise you won't be able to process large files (i.e. + 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). */ #ifndef MINIZ_HEADER_INCLUDED @@ -163,60 +224,80 @@ #include // Defines to completely disable specific portions of miniz.c: -// If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. +// If all macros here are defined the only functionality remaining will be +// CRC-32, adler-32, tinfl, and tdefl. -// Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. +// Define MINIZ_NO_STDIO to disable all usage and any functions which rely on +// stdio for file I/O. //#define MINIZ_NO_STDIO -// If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or -// get/set file times, and the C run-time funcs that get/set times won't be called. -// The current downside is the times written to your archives will be from 1979. +// If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able +// to get the current time, or get/set file times, and the C run-time funcs that +// get/set times won't be called. The current downside is the times written to +// your archives will be from 1979. //#define MINIZ_NO_TIME // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. //#define MINIZ_NO_ARCHIVE_APIS -// Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's. +// Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive +// API's. //#define MINIZ_NO_ARCHIVE_WRITING_APIS -// Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. +// Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression +// API's. //#define MINIZ_NO_ZLIB_APIS -// Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. +// Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent +// conflicts against stock zlib. //#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. -// Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc -// callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user -// functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. +// Note if MINIZ_NO_MALLOC is defined then the user must always provide custom +// user alloc/free/realloc callbacks to the zlib and archive API's, and a few +// stand-alone helper API's which don't provide custom user functions (such as +// tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. //#define MINIZ_NO_MALLOC #if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) - // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux - #define MINIZ_NO_TIME +// TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc +// on Linux +#define MINIZ_NO_TIME #endif #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) - #include +#include #endif -#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) +#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \ + defined(__i386) || defined(__i486__) || defined(__i486) || \ + defined(i386) || defined(__ia64__) || defined(__x86_64__) // MINIZ_X86_OR_X64_CPU is only used to help set the below macros. #define MINIZ_X86_OR_X64_CPU 1 #endif -#if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU +#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. #define MINIZ_LITTLE_ENDIAN 1 #endif +/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES only if not set */ +#if !defined(MINIZ_USE_UNALIGNED_LOADS_AND_STORES) #if MINIZ_X86_OR_X64_CPU -// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. +/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. */ +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 +#define MINIZ_UNALIGNED_USE_MEMCPY +#else #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 #endif +#endif -#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) -// Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). +#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \ + defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \ + defined(__x86_64__) +// Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are +// reasonably fast (and don't involve compiler generated calls to helper +// functions). #define MINIZ_HAS_64BIT_REGISTERS 1 #endif @@ -225,6 +306,18 @@ #define fseeko64 fseeko #define fopen64 fopen #define freopen64 freopen + +// Darwin OSX +#define MZ_PLATFORM 19 +#endif + +#ifndef MZ_PLATFORM +#if defined(_WIN64) || defined(_WIN32) || defined(__WIN32__) +#define MZ_PLATFORM 0 +#else +// UNIX +#define MZ_PLATFORM 3 +#endif #endif #ifdef __cplusplus @@ -233,22 +326,33 @@ extern "C" { // ------------------- zlib-style API Definitions. -// For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! +// For more compatibility with zlib, miniz.c uses unsigned long for some +// parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! typedef unsigned long mz_ulong; -// mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. +// mz_free() internally uses the MZ_FREE() macro (which by default calls free() +// unless you've modified the MZ_MALLOC macro) to release a block allocated from +// the heap. void mz_free(void *p); #define MZ_ADLER32_INIT (1) -// mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. +// mz_adler32() returns the initial adler-32 value to use when called with +// ptr==NULL. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); #define MZ_CRC32_INIT (0) -// mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. +// mz_crc32() returns the initial CRC-32 value to use when called with +// ptr==NULL. mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); // Compression strategies. -enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; +enum { + MZ_DEFAULT_STRATEGY = 0, + MZ_FILTERED = 1, + MZ_HUFFMAN_ONLY = 2, + MZ_RLE = 3, + MZ_FIXED = 4 +}; // Method #define MZ_DEFLATED 8 @@ -256,26 +360,56 @@ enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3 #ifndef MINIZ_NO_ZLIB_APIS // Heap allocation callbacks. -// Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. +// Note that mz_alloc_func parameter types purpsosely differ from zlib's: +// items/size is size_t, not unsigned long. typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); typedef void (*mz_free_func)(void *opaque, void *address); -typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); +typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, + size_t size); -#define MZ_VERSION "9.1.15" -#define MZ_VERNUM 0x91F0 -#define MZ_VER_MAJOR 9 -#define MZ_VER_MINOR 1 -#define MZ_VER_REVISION 15 -#define MZ_VER_SUBREVISION 0 +#define MZ_VERSION "9.1.15" +#define MZ_VERNUM 0x91F0 +#define MZ_VER_MAJOR 9 +#define MZ_VER_MINOR 1 +#define MZ_VER_REVISION 15 +#define MZ_VER_SUBREVISION 0 -// Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). -enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; +// Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The +// other values are for advanced use (refer to the zlib docs). +enum { + MZ_NO_FLUSH = 0, + MZ_PARTIAL_FLUSH = 1, + MZ_SYNC_FLUSH = 2, + MZ_FULL_FLUSH = 3, + MZ_FINISH = 4, + MZ_BLOCK = 5 +}; // Return status codes. MZ_PARAM_ERROR is non-standard. -enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; +enum { + MZ_OK = 0, + MZ_STREAM_END = 1, + MZ_NEED_DICT = 2, + MZ_ERRNO = -1, + MZ_STREAM_ERROR = -2, + MZ_DATA_ERROR = -3, + MZ_MEM_ERROR = -4, + MZ_BUF_ERROR = -5, + MZ_VERSION_ERROR = -6, + MZ_PARAM_ERROR = -10000 +}; -// Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. -enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; +// Compression levels: 0-9 are the standard zlib-style levels, 10 is best +// possible compression (not zlib compatible, and may be very slow), +// MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. +enum { + MZ_NO_COMPRESSION = 0, + MZ_BEST_SPEED = 1, + MZ_BEST_COMPRESSION = 9, + MZ_UBER_COMPRESSION = 10, + MZ_DEFAULT_LEVEL = 6, + MZ_DEFAULT_COMPRESSION = -1 +}; // Window bits #define MZ_DEFAULT_WINDOW_BITS 15 @@ -283,26 +417,26 @@ enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBE struct mz_internal_state; // Compression/decompression stream struct. -typedef struct mz_stream_s -{ - const unsigned char *next_in; // pointer to next byte to read - unsigned int avail_in; // number of bytes available at next_in - mz_ulong total_in; // total number of bytes consumed so far +typedef struct mz_stream_s { + const unsigned char *next_in; // pointer to next byte to read + unsigned int avail_in; // number of bytes available at next_in + mz_ulong total_in; // total number of bytes consumed so far - unsigned char *next_out; // pointer to next byte to write - unsigned int avail_out; // number of bytes that can be written to next_out - mz_ulong total_out; // total number of bytes produced so far + unsigned char *next_out; // pointer to next byte to write + unsigned int avail_out; // number of bytes that can be written to next_out + mz_ulong total_out; // total number of bytes produced so far - char *msg; // error msg (unused) - struct mz_internal_state *state; // internal state, allocated by zalloc/zfree + char *msg; // error msg (unused) + struct mz_internal_state *state; // internal state, allocated by zalloc/zfree - mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) - mz_free_func zfree; // optional heap free function (defaults to free) - void *opaque; // heap alloc function user pointer + mz_alloc_func + zalloc; // optional heap allocation function (defaults to malloc) + mz_free_func zfree; // optional heap free function (defaults to free) + void *opaque; // heap alloc function user pointer - int data_type; // data_type (unused) - mz_ulong adler; // adler32 of the source or uncompressed data - mz_ulong reserved; // not used + int data_type; // data_type (unused) + mz_ulong adler; // adler32 of the source or uncompressed data + mz_ulong reserved; // not used } mz_stream; typedef mz_stream *mz_streamp; @@ -314,8 +448,10 @@ const char *mz_version(void); // Parameters: // pStream must point to an initialized mz_stream struct. // level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. -// level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. -// (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) +// level 1 enables a specially optimized compression function that's been +// optimized purely for performance, not ratio. (This special func. is +// currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and +// MINIZ_LITTLE_ENDIAN are defined.) // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. @@ -326,23 +462,32 @@ int mz_deflateInit(mz_streamp pStream, int level); // mz_deflateInit2() is like mz_deflate(), except with more control: // Additional parameters: // method must be MZ_DEFLATED -// window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) -// mem_level must be between [1, 9] (it's checked but ignored by miniz.c) -int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); +// window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with +// zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no +// header or footer) mem_level must be between [1, 9] (it's checked but +// ignored by miniz.c) +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, + int mem_level, int strategy); -// Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). +// Quickly resets a compressor without having to reallocate anything. Same as +// calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). int mz_deflateReset(mz_streamp pStream); -// mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. -// Parameters: -// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. -// flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. +// mz_deflate() compresses the input to output, consuming as much of the input +// and producing as much output as possible. Parameters: +// pStream is the stream to read from and write to. You must initialize/update +// the next_in, avail_in, next_out, and avail_out members. flush may be +// MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. // Return values: -// MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). -// MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. +// MZ_OK on success (when flushing, or if more input is needed but not +// available, and/or there's more output to be written but the output buffer +// is full). MZ_STREAM_END if all input has been consumed and all output bytes +// have been written. Don't call mz_deflate() on the stream anymore. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if one of the parameters is invalid. -// MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) +// MZ_BUF_ERROR if no forward progress is possible because the input and/or +// output buffers are empty. (Fill up the input buffer or free up some output +// space and try again.) int mz_deflate(mz_streamp pStream, int flush); // mz_deflateEnd() deinitializes a compressor: @@ -351,123 +496,145 @@ int mz_deflate(mz_streamp pStream, int flush); // MZ_STREAM_ERROR if the stream is bogus. int mz_deflateEnd(mz_streamp pStream); -// mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. +// mz_deflateBound() returns a (very) conservative upper bound on the amount of +// data that could be generated by deflate(), assuming flush is set to only +// MZ_NO_FLUSH or MZ_FINISH. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); // Single-call compression functions mz_compress() and mz_compress2(): -// Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. -int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); -int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); +// Returns MZ_OK on success, or one of the error codes from mz_deflate() on +// failure. +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, + const unsigned char *pSource, mz_ulong source_len); +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, + const unsigned char *pSource, mz_ulong source_len, int level); -// mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). +// mz_compressBound() returns a (very) conservative upper bound on the amount of +// data that could be generated by calling mz_compress(). mz_ulong mz_compressBound(mz_ulong source_len); // Initializes a decompressor. int mz_inflateInit(mz_streamp pStream); -// mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: -// window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). +// mz_inflateInit2() is like mz_inflateInit() with an additional option that +// controls the window size and whether or not the stream has been wrapped with +// a zlib header/footer: window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse +// zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). int mz_inflateInit2(mz_streamp pStream, int window_bits); -// Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. -// Parameters: -// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. -// flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. -// On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). -// MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. +// Decompresses the input stream to the output, consuming only as much of the +// input as needed, and writing as much to the output as possible. Parameters: +// pStream is the stream to read from and write to. You must initialize/update +// the next_in, avail_in, next_out, and avail_out members. flush may be +// MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. On the first call, if flush is +// MZ_FINISH it's assumed the input and output buffers are both sized large +// enough to decompress the entire stream in a single call (this is slightly +// faster). MZ_FINISH implies that there are no more source bytes available +// beside what's already in the input buffer, and that the output buffer is +// large enough to hold the rest of the decompressed data. // Return values: -// MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. -// MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. -// MZ_STREAM_ERROR if the stream is bogus. +// MZ_OK on success. Either more input is needed but not available, and/or +// there's more output to be written but the output buffer is full. +// MZ_STREAM_END if all needed input has been consumed and all output bytes +// have been written. For zlib streams, the adler-32 of the decompressed data +// has also been verified. MZ_STREAM_ERROR if the stream is bogus. // MZ_DATA_ERROR if the deflate stream is invalid. // MZ_PARAM_ERROR if one of the parameters is invalid. -// MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again -// with more input data, or with more room in the output buffer (except when using single call decompression, described above). +// MZ_BUF_ERROR if no forward progress is possible because the input buffer is +// empty but the inflater needs more input to continue, or if the output +// buffer is not large enough. Call mz_inflate() again with more input data, +// or with more room in the output buffer (except when using single call +// decompression, described above). int mz_inflate(mz_streamp pStream, int flush); // Deinitializes a decompressor. int mz_inflateEnd(mz_streamp pStream); // Single-call decompression. -// Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. -int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); +// Returns MZ_OK on success, or one of the error codes from mz_inflate() on +// failure. +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, + const unsigned char *pSource, mz_ulong source_len); -// Returns a string description of the specified error code, or NULL if the error code is invalid. +// Returns a string description of the specified error code, or NULL if the +// error code is invalid. const char *mz_error(int err); -// Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. -// Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. +// Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used +// as a drop-in replacement for the subset of zlib that miniz.c supports. Define +// MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib +// in the same project. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES - typedef unsigned char Byte; - typedef unsigned int uInt; - typedef mz_ulong uLong; - typedef Byte Bytef; - typedef uInt uIntf; - typedef char charf; - typedef int intf; - typedef void *voidpf; - typedef uLong uLongf; - typedef void *voidp; - typedef void *const voidpc; - #define Z_NULL 0 - #define Z_NO_FLUSH MZ_NO_FLUSH - #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH - #define Z_SYNC_FLUSH MZ_SYNC_FLUSH - #define Z_FULL_FLUSH MZ_FULL_FLUSH - #define Z_FINISH MZ_FINISH - #define Z_BLOCK MZ_BLOCK - #define Z_OK MZ_OK - #define Z_STREAM_END MZ_STREAM_END - #define Z_NEED_DICT MZ_NEED_DICT - #define Z_ERRNO MZ_ERRNO - #define Z_STREAM_ERROR MZ_STREAM_ERROR - #define Z_DATA_ERROR MZ_DATA_ERROR - #define Z_MEM_ERROR MZ_MEM_ERROR - #define Z_BUF_ERROR MZ_BUF_ERROR - #define Z_VERSION_ERROR MZ_VERSION_ERROR - #define Z_PARAM_ERROR MZ_PARAM_ERROR - #define Z_NO_COMPRESSION MZ_NO_COMPRESSION - #define Z_BEST_SPEED MZ_BEST_SPEED - #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION - #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION - #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY - #define Z_FILTERED MZ_FILTERED - #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY - #define Z_RLE MZ_RLE - #define Z_FIXED MZ_FIXED - #define Z_DEFLATED MZ_DEFLATED - #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS - #define alloc_func mz_alloc_func - #define free_func mz_free_func - #define internal_state mz_internal_state - #define z_stream mz_stream - #define deflateInit mz_deflateInit - #define deflateInit2 mz_deflateInit2 - #define deflateReset mz_deflateReset - #define deflate mz_deflate - #define deflateEnd mz_deflateEnd - #define deflateBound mz_deflateBound - #define compress mz_compress - #define compress2 mz_compress2 - #define compressBound mz_compressBound - #define inflateInit mz_inflateInit - #define inflateInit2 mz_inflateInit2 - #define inflate mz_inflate - #define inflateEnd mz_inflateEnd - #define uncompress mz_uncompress - #define crc32 mz_crc32 - #define adler32 mz_adler32 - #define MAX_WBITS 15 - #define MAX_MEM_LEVEL 9 - #define zError mz_error - #define ZLIB_VERSION MZ_VERSION - #define ZLIB_VERNUM MZ_VERNUM - #define ZLIB_VER_MAJOR MZ_VER_MAJOR - #define ZLIB_VER_MINOR MZ_VER_MINOR - #define ZLIB_VER_REVISION MZ_VER_REVISION - #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION - #define zlibVersion mz_version - #define zlib_version mz_version() +typedef unsigned char Byte; +typedef unsigned int uInt; +typedef mz_ulong uLong; +typedef Byte Bytef; +typedef uInt uIntf; +typedef char charf; +typedef int intf; +typedef void *voidpf; +typedef uLong uLongf; +typedef void *voidp; +typedef void *const voidpc; +#define Z_NULL 0 +#define Z_NO_FLUSH MZ_NO_FLUSH +#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH +#define Z_SYNC_FLUSH MZ_SYNC_FLUSH +#define Z_FULL_FLUSH MZ_FULL_FLUSH +#define Z_FINISH MZ_FINISH +#define Z_BLOCK MZ_BLOCK +#define Z_OK MZ_OK +#define Z_STREAM_END MZ_STREAM_END +#define Z_NEED_DICT MZ_NEED_DICT +#define Z_ERRNO MZ_ERRNO +#define Z_STREAM_ERROR MZ_STREAM_ERROR +#define Z_DATA_ERROR MZ_DATA_ERROR +#define Z_MEM_ERROR MZ_MEM_ERROR +#define Z_BUF_ERROR MZ_BUF_ERROR +#define Z_VERSION_ERROR MZ_VERSION_ERROR +#define Z_PARAM_ERROR MZ_PARAM_ERROR +#define Z_NO_COMPRESSION MZ_NO_COMPRESSION +#define Z_BEST_SPEED MZ_BEST_SPEED +#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION +#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION +#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY +#define Z_FILTERED MZ_FILTERED +#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY +#define Z_RLE MZ_RLE +#define Z_FIXED MZ_FIXED +#define Z_DEFLATED MZ_DEFLATED +#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS +#define alloc_func mz_alloc_func +#define free_func mz_free_func +#define internal_state mz_internal_state +#define z_stream mz_stream +#define deflateInit mz_deflateInit +#define deflateInit2 mz_deflateInit2 +#define deflateReset mz_deflateReset +#define deflate mz_deflate +#define deflateEnd mz_deflateEnd +#define deflateBound mz_deflateBound +#define compress mz_compress +#define compress2 mz_compress2 +#define compressBound mz_compressBound +#define inflateInit mz_inflateInit +#define inflateInit2 mz_inflateInit2 +#define inflate mz_inflate +#define inflateEnd mz_inflateEnd +#define uncompress mz_uncompress +#define crc32 mz_crc32 +#define adler32 mz_adler32 +#define MAX_WBITS 15 +#define MAX_MEM_LEVEL 9 +#define zError mz_error +#define ZLIB_VERSION MZ_VERSION +#define ZLIB_VERNUM MZ_VERNUM +#define ZLIB_VER_MAJOR MZ_VER_MAJOR +#define ZLIB_VER_MINOR MZ_VER_MINOR +#define ZLIB_VER_REVISION MZ_VER_REVISION +#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION +#define zlibVersion mz_version +#define zlib_version mz_version() #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES #endif // MINIZ_NO_ZLIB_APIS @@ -486,26 +653,25 @@ typedef int mz_bool; #define MZ_FALSE (0) #define MZ_TRUE (1) -// An attempt to work around MSVC's spammy "warning C4127: conditional expression is constant" message. +// An attempt to work around MSVC's spammy "warning C4127: conditional +// expression is constant" message. #ifdef _MSC_VER - #define MZ_MACRO_END while (0, 0) +#define MZ_MACRO_END while (0, 0) #else - #define MZ_MACRO_END while (0) +#define MZ_MACRO_END while (0) #endif // ------------------- ZIP archive reading/writing #ifndef MINIZ_NO_ARCHIVE_APIS -enum -{ - MZ_ZIP_MAX_IO_BUF_SIZE = 64*1024, +enum { + MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 }; -typedef struct -{ +typedef struct { mz_uint32 m_file_index; mz_uint32 m_central_dir_ofs; mz_uint16 m_version_made_by; @@ -526,22 +692,22 @@ typedef struct char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; } mz_zip_archive_file_stat; -typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); -typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); +typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, + void *pBuf, size_t n); +typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, + const void *pBuf, size_t n); struct mz_zip_internal_state_tag; typedef struct mz_zip_internal_state_tag mz_zip_internal_state; -typedef enum -{ +typedef enum { MZ_ZIP_MODE_INVALID = 0, MZ_ZIP_MODE_READING = 1, MZ_ZIP_MODE_WRITING = 2, MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 } mz_zip_mode; -typedef struct mz_zip_archive_tag -{ +typedef struct mz_zip_archive_tag { mz_uint64 m_archive_size; mz_uint64 m_central_directory_file_ofs; mz_uint m_total_files; @@ -562,11 +728,10 @@ typedef struct mz_zip_archive_tag } mz_zip_archive; -typedef enum -{ - MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, - MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, - MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, +typedef enum { + MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, + MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, + MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 } mz_zip_flags; @@ -574,56 +739,91 @@ typedef enum // Inits a ZIP archive reader. // These functions read and validate the archive's central directory. -mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags); -mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags); +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, + mz_uint32 flags); +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, + size_t size, mz_uint32 flags); #ifndef MINIZ_NO_STDIO -mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, + mz_uint32 flags); #endif // Returns the total number of files in the archive. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); // Returns detailed information about an archive file entry. -mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, + mz_zip_archive_file_stat *pStat); // Determines if an archive file entry is a directory entry. -mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); -mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, + mz_uint file_index); +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, + mz_uint file_index); // Retrieves the filename of an archive file entry. -// Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. -mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); +// Returns the number of bytes written to pFilename, or if filename_buf_size is +// 0 this function returns the number of bytes needed to fully store the +// filename. +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, + char *pFilename, mz_uint filename_buf_size); // Attempts to locates a file in the archive's central directory. // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH // Returns -1 if the file cannot be found. -int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, + const char *pComment, mz_uint flags); // Extracts a archive file to a memory buffer using no memory allocation. -mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); -mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, + mz_uint file_index, void *pBuf, + size_t buf_size, mz_uint flags, + void *pUser_read_buf, + size_t user_read_buf_size); +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( + mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, + mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); // Extracts a archive file to a memory buffer. -mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); -mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, + void *pBuf, size_t buf_size, + mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, + const char *pFilename, void *pBuf, + size_t buf_size, mz_uint flags); // Extracts a archive file to a dynamically allocated heap buffer. -void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); -void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, + size_t *pSize, mz_uint flags); +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, + const char *pFilename, size_t *pSize, + mz_uint flags); // Extracts a archive file using a callback function to output the file's data. -mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); -mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, + mz_uint file_index, + mz_file_write_func pCallback, + void *pOpaque, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, + const char *pFilename, + mz_file_write_func pCallback, + void *pOpaque, mz_uint flags); #ifndef MINIZ_NO_STDIO -// Extracts a archive file to a disk file and sets its last accessed and modified times. -// This function only extracts files, not archive directory records. -mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); -mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); +// Extracts a archive file to a disk file and sets its last accessed and +// modified times. This function only extracts files, not archive directory +// records. +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, + const char *pDst_filename, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, + const char *pArchive_filename, + const char *pDst_filename, + mz_uint flags); #endif -// Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. +// Ends archive reading, freeing all allocations, and closing the input archive +// file if mz_zip_reader_init_file() was used. mz_bool mz_zip_reader_end(mz_zip_archive *pZip); // ZIP archive writing @@ -632,55 +832,93 @@ mz_bool mz_zip_reader_end(mz_zip_archive *pZip); // Inits a ZIP archive writer. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); -mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, + size_t size_to_reserve_at_beginning, + size_t initial_allocation_size); #ifndef MINIZ_NO_STDIO -mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, + mz_uint64 size_to_reserve_at_beginning); #endif -// Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. -// For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. -// For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). -// Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. -// Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before -// the archive is finalized the file's central directory will be hosed. -mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); +// Converts a ZIP archive reader object into a writer object, to allow efficient +// in-place file appends to occur on an existing archive. For archives opened +// using mz_zip_reader_init_file, pFilename must be the archive's filename so it +// can be reopened for writing. If the file can't be reopened, +// mz_zip_reader_end() will be called. For archives opened using +// mz_zip_reader_init_mem, the memory block must be growable using the realloc +// callback (which defaults to realloc unless you've overridden it). Finally, +// for archives opened using mz_zip_reader_init, the mz_zip_archive's user +// provided m_pWrite function cannot be NULL. Note: In-place archive +// modification is not recommended unless you know what you're doing, because if +// execution stops or something goes wrong before the archive is finalized the +// file's central directory will be hosed. +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, + const char *pFilename); -// Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. -// To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer. -// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. -mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); -mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); +// Adds the contents of a memory buffer to an archive. These functions record +// the current local time into the archive. To add a directory entry, call this +// method with an archive name ending in a forwardslash with empty buffer. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, +// MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or +// just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, + const void *pBuf, size_t buf_size, + mz_uint level_and_flags); +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, + const char *pArchive_name, const void *pBuf, + size_t buf_size, const void *pComment, + mz_uint16 comment_size, + mz_uint level_and_flags, mz_uint64 uncomp_size, + mz_uint32 uncomp_crc32); #ifndef MINIZ_NO_STDIO -// Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. -// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. -mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); +// Adds the contents of a disk file to an archive. This function also records +// the disk file's modified time into the archive. level_and_flags - compression +// level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd +// with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, + const char *pSrc_filename, const void *pComment, + mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint32 ext_attributes); #endif // Adds a file to an archive by fully cloning the data from another archive. -// This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields. -mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index); +// This function fully clones the source file's compressed data (no +// recompression), along with its full filename, extra data, and comment fields. +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, + mz_zip_archive *pSource_zip, + mz_uint file_index); -// Finalizes the archive by writing the central directory records followed by the end of central directory record. -// After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). -// An archive must be manually finalized by calling this function for it to be valid. +// Finalizes the archive by writing the central directory records followed by +// the end of central directory record. After an archive is finalized, the only +// valid call on the mz_zip_archive struct is mz_zip_writer_end(). An archive +// must be manually finalized by calling this function for it to be valid. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); -mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize); +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, + size_t *pSize); -// Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. -// Note for the archive to be valid, it must have been finalized before ending. +// Ends archive writing, freeing all allocations, and closing the output file if +// mz_zip_writer_init_file() was used. Note for the archive to be valid, it must +// have been finalized before ending. mz_bool mz_zip_writer_end(mz_zip_archive *pZip); // Misc. high-level helper functions: -// mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. -// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. -mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); +// mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) +// appends a memory blob to a ZIP archive. level_and_flags - compression level +// (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero +// or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_add_mem_to_archive_file_in_place( + const char *pZip_filename, const char *pArchive_name, const void *pBuf, + size_t buf_size, const void *pComment, mz_uint16 comment_size, + mz_uint level_and_flags); // Reads a single file from an archive into a heap block. // Returns NULL on failure. -void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, + const char *pArchive_name, + size_t *pSize, mz_uint zip_flags); #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS @@ -689,12 +927,17 @@ void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char // ------------------- Low-level Decompression API Definitions // Decompression flags used by tinfl_decompress(). -// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. -// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. -// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). -// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. -enum -{ +// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and +// ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the +// input is a raw deflate stream. TINFL_FLAG_HAS_MORE_INPUT: If set, there are +// more input bytes available beyond the end of the supplied input buffer. If +// clear, the input buffer contains all remaining input. +// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large +// enough to hold the entire decompressed stream. If clear, the output buffer is +// at least the size of the dictionary (typically 32KB). +// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the +// decompressed bytes. +enum { TINFL_FLAG_PARSE_ZLIB_HEADER = 1, TINFL_FLAG_HAS_MORE_INPUT = 2, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, @@ -702,33 +945,42 @@ enum }; // High level decompression functions: -// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). -// On entry: -// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. +// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block +// allocated via malloc(). On entry: +// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data +// to decompress. // On return: // Function returns a pointer to the decompressed data, or NULL on failure. -// *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. -// The caller must call mz_free() on the returned block when it's no longer needed. -void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); +// *pOut_len will be set to the decompressed data's size, which could be larger +// than src_buf_len on uncompressible data. The caller must call mz_free() on +// the returned block when it's no longer needed. +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, + size_t *pOut_len, int flags); -// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. -// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. +// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block +// in memory. Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the +// number of bytes written on success. #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) -size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, + const void *pSrc_buf, size_t src_buf_len, + int flags); -// tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. -// Returns 1 on success or 0 on failure. -typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); -int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); +// tinfl_decompress_mem_to_callback() decompresses a block in memory to an +// internal 32KB buffer, and a user provided callback function will be called to +// flush the buffer. Returns 1 on success or 0 on failure. +typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, + tinfl_put_buf_func_ptr pPut_buf_func, + void *pPut_buf_user, int flags); -struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; +struct tinfl_decompressor_tag; +typedef struct tinfl_decompressor_tag tinfl_decompressor; // Max size of LZ dictionary. #define TINFL_LZ_DICT_SIZE 32768 // Return status. -typedef enum -{ +typedef enum { TINFL_STATUS_BAD_PARAM = -3, TINFL_STATUS_ADLER32_MISMATCH = -2, TINFL_STATUS_FAILED = -1, @@ -738,126 +990,196 @@ typedef enum } tinfl_status; // Initializes the decompressor to its initial state. -#define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END +#define tinfl_init(r) \ + do { \ + (r)->m_state = 0; \ + } \ + MZ_MACRO_END #define tinfl_get_adler32(r) (r)->m_check_adler32 -// Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. -// This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. -tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); +// Main low-level decompressor coroutine function. This is the only function +// actually needed for decompression. All the other functions are just +// high-level helpers for improved usability. This is a universal API, i.e. it +// can be used as a building block to build any desired higher level +// decompression API. In the limit case, it can be called once per every byte +// input or output. +tinfl_status tinfl_decompress(tinfl_decompressor *r, + const mz_uint8 *pIn_buf_next, + size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, + mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, + const mz_uint32 decomp_flags); // Internal/private bits follow. -enum -{ - TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, - TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS +enum { + TINFL_MAX_HUFF_TABLES = 3, + TINFL_MAX_HUFF_SYMBOLS_0 = 288, + TINFL_MAX_HUFF_SYMBOLS_1 = 32, + TINFL_MAX_HUFF_SYMBOLS_2 = 19, + TINFL_FAST_LOOKUP_BITS = 10, + TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS }; -typedef struct -{ +typedef struct { mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; - mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; + mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], + m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; } tinfl_huff_table; #if MINIZ_HAS_64BIT_REGISTERS - #define TINFL_USE_64BIT_BITBUF 1 +#define TINFL_USE_64BIT_BITBUF 1 #endif #if TINFL_USE_64BIT_BITBUF - typedef mz_uint64 tinfl_bit_buf_t; - #define TINFL_BITBUF_SIZE (64) +typedef mz_uint64 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (64) #else - typedef mz_uint32 tinfl_bit_buf_t; - #define TINFL_BITBUF_SIZE (32) +typedef mz_uint32 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (32) #endif -struct tinfl_decompressor_tag -{ - mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; +struct tinfl_decompressor_tag { + mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, + m_check_adler32, m_dist, m_counter, m_num_extra, + m_table_sizes[TINFL_MAX_HUFF_TABLES]; tinfl_bit_buf_t m_bit_buf; size_t m_dist_from_out_buf_start; tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; - mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; + mz_uint8 m_raw_header[4], + m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; }; // ------------------- Low-level Compression API Definitions -// Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). +// Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly +// slower, and raw/dynamic blocks will be output more frequently). #define TDEFL_LESS_MEMORY 0 -// tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): -// TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). -enum -{ - TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF +// tdefl_init() compression flags logically OR'd together (low 12 bits contain +// the max. number of probes per dictionary search): TDEFL_DEFAULT_MAX_PROBES: +// The compressor defaults to 128 dictionary probes per dictionary search. +// 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ +// (slowest/best compression). +enum { + TDEFL_HUFFMAN_ONLY = 0, + TDEFL_DEFAULT_MAX_PROBES = 128, + TDEFL_MAX_PROBES_MASK = 0xFFF }; -// TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. -// TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). -// TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. -// TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). -// TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) -// TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. +// TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before +// the deflate data, and the Adler-32 of the source data at the end. Otherwise, +// you'll get raw deflate data. TDEFL_COMPUTE_ADLER32: Always compute the +// adler-32 of the input data (even when not writing zlib headers). +// TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more +// efficient lazy parsing. TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to +// decrease the compressor's initialization time to the minimum, but the output +// may vary from run to run given the same input (depending on the contents of +// memory). TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a +// distance of 1) TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. -// The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). -enum -{ - TDEFL_WRITE_ZLIB_HEADER = 0x01000, - TDEFL_COMPUTE_ADLER32 = 0x02000, - TDEFL_GREEDY_PARSING_FLAG = 0x04000, +// The low 12 bits are reserved to control the max # of hash probes per +// dictionary lookup (see TDEFL_MAX_PROBES_MASK). +enum { + TDEFL_WRITE_ZLIB_HEADER = 0x01000, + TDEFL_COMPUTE_ADLER32 = 0x02000, + TDEFL_GREEDY_PARSING_FLAG = 0x04000, TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, - TDEFL_RLE_MATCHES = 0x10000, - TDEFL_FILTER_MATCHES = 0x20000, - TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, - TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 + TDEFL_RLE_MATCHES = 0x10000, + TDEFL_FILTER_MATCHES = 0x20000, + TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, + TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 }; // High level compression functions: -// tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). -// On entry: +// tdefl_compress_mem_to_heap() compresses a block in memory to a heap block +// allocated via malloc(). On entry: // pSrc_buf, src_buf_len: Pointer and size of source block to compress. -// flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. +// flags: The max match finder probes (default is 128) logically OR'd against +// the above flags. Higher probes are slower but improve compression. // On return: // Function returns a pointer to the compressed data, or NULL on failure. -// *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. -// The caller must free() the returned block when it's no longer needed. -void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); +// *pOut_len will be set to the compressed data's size, which could be larger +// than src_buf_len on uncompressible data. The caller must free() the returned +// block when it's no longer needed. +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, + size_t *pOut_len, int flags); -// tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. -// Returns 0 on failure. -size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); +// tdefl_compress_mem_to_mem() compresses a block in memory to another block in +// memory. Returns 0 on failure. +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, + const void *pSrc_buf, size_t src_buf_len, + int flags); // Compresses an image to a compressed PNG file in memory. // On entry: -// pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. -// The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. -// level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL -// If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). +// pImage, w, h, and num_chans describe the image to compress. num_chans may be +// 1, 2, 3, or 4. The image pitch in bytes per scanline will be w*num_chans. +// The leftmost pixel on the top scanline is stored first in memory. level may +// range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, +// MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL If flip is +// true, the image will be flipped on the Y axis (useful for OpenGL apps). // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pLen_out will be set to the size of the PNG image file. -// The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. -void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); -void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); +// The caller must mz_free() the returned heap block (which will typically be +// larger than *pLen_out) when it's no longer needed. +void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, + int h, int num_chans, + size_t *pLen_out, + mz_uint level, mz_bool flip); +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, + int num_chans, size_t *pLen_out); -// Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. -typedef mz_bool (*tdefl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); +// Output stream interface. The compressor uses this interface to write +// compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. +typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, + void *pUser); -// tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. -mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); +// tdefl_compress_mem_to_output() compresses a block to an output stream. The +// above helpers use this function internally. +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, + tdefl_put_buf_func_ptr pPut_buf_func, + void *pPut_buf_user, int flags); -enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; +enum { + TDEFL_MAX_HUFF_TABLES = 3, + TDEFL_MAX_HUFF_SYMBOLS_0 = 288, + TDEFL_MAX_HUFF_SYMBOLS_1 = 32, + TDEFL_MAX_HUFF_SYMBOLS_2 = 19, + TDEFL_LZ_DICT_SIZE = 32768, + TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, + TDEFL_MIN_MATCH_LEN = 3, + TDEFL_MAX_MATCH_LEN = 258 +}; -// TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). +// TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed +// output block (using static/fixed Huffman codes). #if TDEFL_LESS_MEMORY -enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; +enum { + TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, + TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, + TDEFL_MAX_HUFF_SYMBOLS = 288, + TDEFL_LZ_HASH_BITS = 12, + TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, + TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, + TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS +}; #else -enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; +enum { + TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, + TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, + TDEFL_MAX_HUFF_SYMBOLS = 288, + TDEFL_LZ_HASH_BITS = 15, + TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, + TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, + TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS +}; #endif -// The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. -typedef enum -{ +// The low-level tdefl functions below may be used directly if the above helper +// functions aren't flexible enough. The low-level functions don't make any heap +// allocations, unlike the above helper functions. +typedef enum { TDEFL_STATUS_BAD_PARAM = -2, TDEFL_STATUS_PUT_BUF_FAILED = -1, TDEFL_STATUS_OKAY = 0, @@ -865,8 +1187,7 @@ typedef enum } tdefl_status; // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums -typedef enum -{ +typedef enum { TDEFL_NO_FLUSH = 0, TDEFL_SYNC_FLUSH = 2, TDEFL_FULL_FLUSH = 3, @@ -874,16 +1195,18 @@ typedef enum } tdefl_flush; // tdefl's compression state structure. -typedef struct -{ +typedef struct { tdefl_put_buf_func_ptr m_pPut_buf_func; void *m_pPut_buf_user; mz_uint m_flags, m_max_probes[2]; int m_greedy_parsing; mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; - mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; - mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; + mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, + m_bit_buffer; + mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, + m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, + m_wants_to_finish; tdefl_status m_prev_return_status; const void *m_pIn_buf; void *m_pOut_buf; @@ -902,29 +1225,42 @@ typedef struct } tdefl_compressor; // Initializes the compressor. -// There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. -// pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. -// If pBut_buf_func is NULL the user should always call the tdefl_compress() API. -// flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) -tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); +// There is no corresponding deinit() function because the tdefl API's do not +// dynamically allocate memory. pBut_buf_func: If NULL, output data will be +// supplied to the specified callback. In this case, the user should call the +// tdefl_compress_buffer() API for compression. If pBut_buf_func is NULL the +// user should always call the tdefl_compress() API. flags: See the above enums +// (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) +tdefl_status tdefl_init(tdefl_compressor *d, + tdefl_put_buf_func_ptr pPut_buf_func, + void *pPut_buf_user, int flags); -// Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. -tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); +// Compresses a block of data, consuming as much of the specified input buffer +// as possible, and writing as much compressed data to the specified output +// buffer as possible. +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, + size_t *pIn_buf_size, void *pOut_buf, + size_t *pOut_buf_size, tdefl_flush flush); -// tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. -// tdefl_compress_buffer() always consumes the entire input buffer. -tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); +// tdefl_compress_buffer() is only usable when the tdefl_init() is called with a +// non-NULL tdefl_put_buf_func_ptr. tdefl_compress_buffer() always consumes the +// entire input buffer. +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, + size_t in_buf_size, tdefl_flush flush); tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); mz_uint32 tdefl_get_adler32(tdefl_compressor *d); -// Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros. +// Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't +// defined, because it uses some of its macros. #ifndef MINIZ_NO_ZLIB_APIS // Create tdefl_compress() flags given zlib-style compression parameters. -// level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) -// window_bits may be -15 (raw deflate) or 15 (zlib) -// strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED -mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); +// level may range from [0,10] (where 10 is absolute max compression, but may be +// much slower on some files) window_bits may be -15 (raw deflate) or 15 (zlib) +// strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, +// MZ_RLE, or MZ_FIXED +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, + int strategy); #endif // #ifndef MINIZ_NO_ZLIB_APIS #ifdef __cplusplus @@ -933,109 +1269,145 @@ mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int #endif // MINIZ_HEADER_INCLUDED -// ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.) +// ------------------- End of Header: Implementation follows. (If you only want +// the header, define MINIZ_HEADER_FILE_ONLY.) #ifndef MINIZ_HEADER_FILE_ONLY -typedef unsigned char mz_validate_uint16[sizeof(mz_uint16)==2 ? 1 : -1]; -typedef unsigned char mz_validate_uint32[sizeof(mz_uint32)==4 ? 1 : -1]; -typedef unsigned char mz_validate_uint64[sizeof(mz_uint64)==8 ? 1 : -1]; +typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; +typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; +typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; -#include #include +#include #define MZ_ASSERT(x) assert(x) #ifdef MINIZ_NO_MALLOC - #define MZ_MALLOC(x) NULL - #define MZ_FREE(x) (void)x, ((void)0) - #define MZ_REALLOC(p, x) NULL +#define MZ_MALLOC(x) NULL +#define MZ_FREE(x) (void)x, ((void)0) +#define MZ_REALLOC(p, x) NULL #else - #define MZ_MALLOC(x) malloc(x) - #define MZ_FREE(x) free(x) - #define MZ_REALLOC(p, x) realloc(p, x) +#define MZ_MALLOC(x) malloc(x) +#define MZ_FREE(x) free(x) +#define MZ_REALLOC(p, x) realloc(p, x) #endif -#define MZ_MAX(a,b) (((a)>(b))?(a):(b)) -#define MZ_MIN(a,b) (((a)<(b))?(a):(b)) +#define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) +#define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN - #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) - #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) +#define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) +#define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) #else - #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) - #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) +#define MZ_READ_LE16(p) \ + ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ + ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) +#define MZ_READ_LE32(p) \ + ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ + ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \ + ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | \ + ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) #endif #ifdef _MSC_VER - #define MZ_FORCEINLINE __forceinline +#define MZ_FORCEINLINE __forceinline #elif defined(__GNUC__) - #define MZ_FORCEINLINE inline __attribute__((__always_inline__)) +#define MZ_FORCEINLINE inline __attribute__((__always_inline__)) #else - #define MZ_FORCEINLINE inline +#define MZ_FORCEINLINE inline #endif #ifdef __cplusplus - extern "C" { +extern "C" { #endif // ------------------- zlib-style API's -mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) -{ - mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552; - if (!ptr) return MZ_ADLER32_INIT; +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) { + mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); + size_t block_len = buf_len % 5552; + if (!ptr) + return MZ_ADLER32_INIT; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { - s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; - s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; + s1 += ptr[0], s2 += s1; + s1 += ptr[1], s2 += s1; + s1 += ptr[2], s2 += s1; + s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; + s1 += ptr[5], s2 += s1; + s1 += ptr[6], s2 += s1; + s1 += ptr[7], s2 += s1; } - for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; - s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; + for (; i < block_len; ++i) + s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; + buf_len -= block_len; + block_len = 5552; } return (s2 << 16) + s1; } -// Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ -mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) -{ - static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, - 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; +// Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C +// implementation that balances processor cache usage against speed": +// http://www.geocities.com/malbrain/ +mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) { + static const mz_uint32 s_crc32[16] = { + 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, + 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, + 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c}; mz_uint32 crcu32 = (mz_uint32)crc; - if (!ptr) return MZ_CRC32_INIT; - crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } + if (!ptr) + return MZ_CRC32_INIT; + crcu32 = ~crcu32; + while (buf_len--) { + mz_uint8 b = *ptr++; + crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; + crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; + } return ~crcu32; } -void mz_free(void *p) -{ - MZ_FREE(p); -} +void mz_free(void *p) { MZ_FREE(p); } #ifndef MINIZ_NO_ZLIB_APIS -static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); } -static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); } -static void *def_realloc_func(void *opaque, void *address, size_t items, size_t size) { (void)opaque, (void)address, (void)items, (void)size; return MZ_REALLOC(address, items * size); } - -const char *mz_version(void) -{ - return MZ_VERSION; +static void *def_alloc_func(void *opaque, size_t items, size_t size) { + (void)opaque, (void)items, (void)size; + return MZ_MALLOC(items * size); +} +static void def_free_func(void *opaque, void *address) { + (void)opaque, (void)address; + MZ_FREE(address); +} +static void *def_realloc_func(void *opaque, void *address, size_t items, + size_t size) { + (void)opaque, (void)address, (void)items, (void)size; + return MZ_REALLOC(address, items * size); } -int mz_deflateInit(mz_streamp pStream, int level) -{ - return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); +const char *mz_version(void) { return MZ_VERSION; } + +int mz_deflateInit(mz_streamp pStream, int level) { + return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, + MZ_DEFAULT_STRATEGY); } -int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) -{ +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, + int mem_level, int strategy) { tdefl_compressor *pComp; - mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); + mz_uint comp_flags = + TDEFL_COMPUTE_ADLER32 | + tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); - if (!pStream) return MZ_STREAM_ERROR; - if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR; + if (!pStream) + return MZ_STREAM_ERROR; + if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || + ((window_bits != MZ_DEFAULT_WINDOW_BITS) && + (-window_bits != MZ_DEFAULT_WINDOW_BITS))) + return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = MZ_ADLER32_INIT; @@ -1043,17 +1415,19 @@ int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, pStream->reserved = 0; pStream->total_in = 0; pStream->total_out = 0; - if (!pStream->zalloc) pStream->zalloc = def_alloc_func; - if (!pStream->zfree) pStream->zfree = def_free_func; + if (!pStream->zalloc) + pStream->zalloc = def_alloc_func; + if (!pStream->zfree) + pStream->zfree = def_free_func; - pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); + pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, + sizeof(tdefl_compressor)); if (!pComp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pComp; - if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) - { + if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) { mz_deflateEnd(pStream); return MZ_PARAM_ERROR; } @@ -1061,56 +1435,64 @@ int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, return MZ_OK; } -int mz_deflateReset(mz_streamp pStream) -{ - if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR; +int mz_deflateReset(mz_streamp pStream) { + if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || + (!pStream->zfree)) + return MZ_STREAM_ERROR; pStream->total_in = pStream->total_out = 0; - tdefl_init((tdefl_compressor*)pStream->state, NULL, NULL, ((tdefl_compressor*)pStream->state)->m_flags); + tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, + ((tdefl_compressor *)pStream->state)->m_flags); return MZ_OK; } -int mz_deflate(mz_streamp pStream, int flush) -{ +int mz_deflate(mz_streamp pStream, int flush) { size_t in_bytes, out_bytes; mz_ulong orig_total_in, orig_total_out; int mz_status = MZ_OK; - if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR; - if (!pStream->avail_out) return MZ_BUF_ERROR; + if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || + (!pStream->next_out)) + return MZ_STREAM_ERROR; + if (!pStream->avail_out) + return MZ_BUF_ERROR; - if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; + if (flush == MZ_PARTIAL_FLUSH) + flush = MZ_SYNC_FLUSH; - if (((tdefl_compressor*)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) + if (((tdefl_compressor *)pStream->state)->m_prev_return_status == + TDEFL_STATUS_DONE) return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; - orig_total_in = pStream->total_in; orig_total_out = pStream->total_out; - for ( ; ; ) - { + orig_total_in = pStream->total_in; + orig_total_out = pStream->total_out; + for (;;) { tdefl_status defl_status; - in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; + in_bytes = pStream->avail_in; + out_bytes = pStream->avail_out; - defl_status = tdefl_compress((tdefl_compressor*)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); - pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; - pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor*)pStream->state); + defl_status = tdefl_compress((tdefl_compressor *)pStream->state, + pStream->next_in, &in_bytes, pStream->next_out, + &out_bytes, (tdefl_flush)flush); + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); - pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; + pStream->next_out += (mz_uint)out_bytes; + pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; - if (defl_status < 0) - { + if (defl_status < 0) { mz_status = MZ_STREAM_ERROR; break; - } - else if (defl_status == TDEFL_STATUS_DONE) - { + } else if (defl_status == TDEFL_STATUS_DONE) { mz_status = MZ_STREAM_END; break; - } - else if (!pStream->avail_out) + } else if (!pStream->avail_out) break; - else if ((!pStream->avail_in) && (flush != MZ_FINISH)) - { - if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) + else if ((!pStream->avail_in) && (flush != MZ_FINISH)) { + if ((flush) || (pStream->total_in != orig_total_in) || + (pStream->total_out != orig_total_out)) break; return MZ_BUF_ERROR; // Can't make forward progress without some input. } @@ -1118,32 +1500,33 @@ int mz_deflate(mz_streamp pStream, int flush) return mz_status; } -int mz_deflateEnd(mz_streamp pStream) -{ - if (!pStream) return MZ_STREAM_ERROR; - if (pStream->state) - { +int mz_deflateEnd(mz_streamp pStream) { + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } -mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) -{ +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) { (void)pStream; - // This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) - return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); + // This is really over conservative. (And lame, but it's actually pretty + // tricky to compute a true upper bound given the way tdefl's blocking works.) + return MZ_MAX(128 + (source_len * 110) / 100, + 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); } -int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) -{ +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, + const unsigned char *pSource, mz_ulong source_len, int level) { int status; mz_stream stream; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). - if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; + if ((source_len | *pDest_len) > 0xFFFFFFFFU) + return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; @@ -1151,11 +1534,11 @@ int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char stream.avail_out = (mz_uint32)*pDest_len; status = mz_deflateInit(&stream, level); - if (status != MZ_OK) return status; + if (status != MZ_OK) + return status; status = mz_deflate(&stream, MZ_FINISH); - if (status != MZ_STREAM_END) - { + if (status != MZ_STREAM_END) { mz_deflateEnd(&stream); return (status == MZ_OK) ? MZ_BUF_ERROR : status; } @@ -1164,29 +1547,31 @@ int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char return mz_deflateEnd(&stream); } -int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) -{ - return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, + const unsigned char *pSource, mz_ulong source_len) { + return mz_compress2(pDest, pDest_len, pSource, source_len, + MZ_DEFAULT_COMPRESSION); } -mz_ulong mz_compressBound(mz_ulong source_len) -{ +mz_ulong mz_compressBound(mz_ulong source_len) { return mz_deflateBound(NULL, source_len); } -typedef struct -{ +typedef struct { tinfl_decompressor m_decomp; - mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits; + mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; + int m_window_bits; mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; tinfl_status m_last_status; } inflate_state; -int mz_inflateInit2(mz_streamp pStream, int window_bits) -{ +int mz_inflateInit2(mz_streamp pStream, int window_bits) { inflate_state *pDecomp; - if (!pStream) return MZ_STREAM_ERROR; - if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR; + if (!pStream) + return MZ_STREAM_ERROR; + if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && + (-window_bits != MZ_DEFAULT_WINDOW_BITS)) + return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = 0; @@ -1194,11 +1579,15 @@ int mz_inflateInit2(mz_streamp pStream, int window_bits) pStream->total_in = 0; pStream->total_out = 0; pStream->reserved = 0; - if (!pStream->zalloc) pStream->zalloc = def_alloc_func; - if (!pStream->zfree) pStream->zfree = def_free_func; + if (!pStream->zalloc) + pStream->zalloc = def_alloc_func; + if (!pStream->zfree) + pStream->zfree = def_free_func; - pDecomp = (inflate_state*)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); - if (!pDecomp) return MZ_MEM_ERROR; + pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, + sizeof(inflate_state)); + if (!pDecomp) + return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pDecomp; @@ -1213,122 +1602,152 @@ int mz_inflateInit2(mz_streamp pStream, int window_bits) return MZ_OK; } -int mz_inflateInit(mz_streamp pStream) -{ - return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); +int mz_inflateInit(mz_streamp pStream) { + return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); } -int mz_inflate(mz_streamp pStream, int flush) -{ - inflate_state* pState; +int mz_inflate(mz_streamp pStream, int flush) { + inflate_state *pState; mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; size_t in_bytes, out_bytes, orig_avail_in; tinfl_status status; - if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR; - if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; - if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; + if ((!pStream) || (!pStream->state)) + return MZ_STREAM_ERROR; + if (flush == MZ_PARTIAL_FLUSH) + flush = MZ_SYNC_FLUSH; + if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) + return MZ_STREAM_ERROR; - pState = (inflate_state*)pStream->state; - if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; + pState = (inflate_state *)pStream->state; + if (pState->m_window_bits > 0) + decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; orig_avail_in = pStream->avail_in; - first_call = pState->m_first_call; pState->m_first_call = 0; - if (pState->m_last_status < 0) return MZ_DATA_ERROR; + first_call = pState->m_first_call; + pState->m_first_call = 0; + if (pState->m_last_status < 0) + return MZ_DATA_ERROR; - if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; + if (pState->m_has_flushed && (flush != MZ_FINISH)) + return MZ_STREAM_ERROR; pState->m_has_flushed |= (flush == MZ_FINISH); - if ((flush == MZ_FINISH) && (first_call)) - { - // MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. + if ((flush == MZ_FINISH) && (first_call)) { + // MZ_FINISH on the first call implies that the input and output buffers are + // large enough to hold the entire compressed/decompressed file. decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; - in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; - status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); + in_bytes = pStream->avail_in; + out_bytes = pStream->avail_out; + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, + pStream->next_out, pStream->next_out, &out_bytes, + decomp_flags); pState->m_last_status = status; - pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); - pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; + pStream->next_out += (mz_uint)out_bytes; + pStream->avail_out -= (mz_uint)out_bytes; + pStream->total_out += (mz_uint)out_bytes; if (status < 0) return MZ_DATA_ERROR; - else if (status != TINFL_STATUS_DONE) - { + else if (status != TINFL_STATUS_DONE) { pState->m_last_status = TINFL_STATUS_FAILED; return MZ_BUF_ERROR; } return MZ_STREAM_END; } // flush != MZ_FINISH then we must assume there's more input. - if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; + if (flush != MZ_FINISH) + decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; - if (pState->m_dict_avail) - { + if (pState->m_dict_avail) { n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); - pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; - pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); - return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; + pStream->next_out += n; + pStream->avail_out -= n; + pStream->total_out += n; + pState->m_dict_avail -= n; + pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + return ((pState->m_last_status == TINFL_STATUS_DONE) && + (!pState->m_dict_avail)) + ? MZ_STREAM_END + : MZ_OK; } - for ( ; ; ) - { + for (;;) { in_bytes = pStream->avail_in; out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; - status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); + status = tinfl_decompress( + &pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, + pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); pState->m_last_status = status; - pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; - pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tinfl_get_adler32(&pState->m_decomp); pState->m_dict_avail = (mz_uint)out_bytes; n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); - pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; - pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + pStream->next_out += n; + pStream->avail_out -= n; + pStream->total_out += n; + pState->m_dict_avail -= n; + pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); if (status < 0) - return MZ_DATA_ERROR; // Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). + return MZ_DATA_ERROR; // Stream is corrupted (there could be some + // uncompressed data left in the output dictionary - + // oh well). else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) - return MZ_BUF_ERROR; // Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. - else if (flush == MZ_FINISH) - { - // The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. - if (status == TINFL_STATUS_DONE) - return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; - // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. - else if (!pStream->avail_out) - return MZ_BUF_ERROR; - } - else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) + return MZ_BUF_ERROR; // Signal caller that we can't make forward progress + // without supplying more input or by setting flush + // to MZ_FINISH. + else if (flush == MZ_FINISH) { + // The output buffer MUST be large to hold the remaining uncompressed data + // when flush==MZ_FINISH. + if (status == TINFL_STATUS_DONE) + return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; + // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's + // at least 1 more byte on the way. If there's no more room left in the + // output buffer then something is wrong. + else if (!pStream->avail_out) + return MZ_BUF_ERROR; + } else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || + (!pStream->avail_out) || (pState->m_dict_avail)) break; } - return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; + return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) + ? MZ_STREAM_END + : MZ_OK; } -int mz_inflateEnd(mz_streamp pStream) -{ +int mz_inflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; - if (pStream->state) - { + if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } -int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) -{ +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, + const unsigned char *pSource, mz_ulong source_len) { mz_stream stream; int status; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). - if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; + if ((source_len | *pDest_len) > 0xFFFFFFFFU) + return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; @@ -1340,268 +1759,482 @@ int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char return status; status = mz_inflate(&stream, MZ_FINISH); - if (status != MZ_STREAM_END) - { + if (status != MZ_STREAM_END) { mz_inflateEnd(&stream); - return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; + return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR + : status; } *pDest_len = stream.total_out; return mz_inflateEnd(&stream); } -const char *mz_error(int err) -{ - static struct { int m_err; const char *m_pDesc; } s_error_descs[] = - { - { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, - { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } - }; - mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc; +const char *mz_error(int err) { + static struct { + int m_err; + const char *m_pDesc; + } s_error_descs[] = {{MZ_OK, ""}, + {MZ_STREAM_END, "stream end"}, + {MZ_NEED_DICT, "need dictionary"}, + {MZ_ERRNO, "file error"}, + {MZ_STREAM_ERROR, "stream error"}, + {MZ_DATA_ERROR, "data error"}, + {MZ_MEM_ERROR, "out of memory"}, + {MZ_BUF_ERROR, "buf error"}, + {MZ_VERSION_ERROR, "version error"}, + {MZ_PARAM_ERROR, "parameter error"}}; + mz_uint i; + for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) + if (s_error_descs[i].m_err == err) + return s_error_descs[i].m_pDesc; return NULL; } -#endif //MINIZ_NO_ZLIB_APIS +#endif // MINIZ_NO_ZLIB_APIS -// ------------------- Low-level Decompression (completely independent from all compression API's) +// ------------------- Low-level Decompression (completely independent from all +// compression API's) #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) #define TINFL_MEMSET(p, c, l) memset(p, c, l) -#define TINFL_CR_BEGIN switch(r->m_state) { case 0: -#define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END -#define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END +#define TINFL_CR_BEGIN \ + switch (r->m_state) { \ + case 0: +#define TINFL_CR_RETURN(state_index, result) \ + do { \ + status = result; \ + r->m_state = state_index; \ + goto common_exit; \ + case state_index:; \ + } \ + MZ_MACRO_END +#define TINFL_CR_RETURN_FOREVER(state_index, result) \ + do { \ + for (;;) { \ + TINFL_CR_RETURN(state_index, result); \ + } \ + } \ + MZ_MACRO_END #define TINFL_CR_FINISH } -// TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never -// reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario. -#define TINFL_GET_BYTE(state_index, c) do { \ - if (pIn_buf_cur >= pIn_buf_end) { \ - for ( ; ; ) { \ - if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ - TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ - if (pIn_buf_cur < pIn_buf_end) { \ - c = *pIn_buf_cur++; \ - break; \ - } \ - } else { \ - c = 0; \ - break; \ - } \ - } \ - } else c = *pIn_buf_cur++; } MZ_MACRO_END +// TODO: If the caller has indicated that there's no more input, and we attempt +// to read beyond the input buf, then something is wrong with the input because +// the inflator never reads ahead more than it needs to. Currently +// TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario. +#define TINFL_GET_BYTE(state_index, c) \ + do { \ + if (pIn_buf_cur >= pIn_buf_end) { \ + for (;;) { \ + if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ + TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ + if (pIn_buf_cur < pIn_buf_end) { \ + c = *pIn_buf_cur++; \ + break; \ + } \ + } else { \ + c = 0; \ + break; \ + } \ + } \ + } else \ + c = *pIn_buf_cur++; \ + } \ + MZ_MACRO_END -#define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n)) -#define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END -#define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END +#define TINFL_NEED_BITS(state_index, n) \ + do { \ + mz_uint c; \ + TINFL_GET_BYTE(state_index, c); \ + bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ + num_bits += 8; \ + } while (num_bits < (mz_uint)(n)) +#define TINFL_SKIP_BITS(state_index, n) \ + do { \ + if (num_bits < (mz_uint)(n)) { \ + TINFL_NEED_BITS(state_index, n); \ + } \ + bit_buf >>= (n); \ + num_bits -= (n); \ + } \ + MZ_MACRO_END +#define TINFL_GET_BITS(state_index, b, n) \ + do { \ + if (num_bits < (mz_uint)(n)) { \ + TINFL_NEED_BITS(state_index, n); \ + } \ + b = bit_buf & ((1 << (n)) - 1); \ + bit_buf >>= (n); \ + num_bits -= (n); \ + } \ + MZ_MACRO_END -// TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. -// It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a -// Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the -// bit buffer contains >=15 bits (deflate's max. Huffman code size). -#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ - do { \ - temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ - if (temp >= 0) { \ - code_len = temp >> 9; \ - if ((code_len) && (num_bits >= code_len)) \ - break; \ - } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ - code_len = TINFL_FAST_LOOKUP_BITS; \ - do { \ - temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ - } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \ - } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \ +// TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes +// remaining in the input buffer falls below 2. It reads just enough bytes from +// the input stream that are needed to decode the next Huffman code (and +// absolutely no more). It works by trying to fully decode a Huffman code by +// using whatever bits are currently present in the bit buffer. If this fails, +// it reads another byte, and tries again until it succeeds or until the bit +// buffer contains >=15 bits (deflate's max. Huffman code size). +#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ + do { \ + temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ + if (temp >= 0) { \ + code_len = temp >> 9; \ + if ((code_len) && (num_bits >= code_len)) \ + break; \ + } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do { \ + temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while ((temp < 0) && (num_bits >= (code_len + 1))); \ + if (temp >= 0) \ + break; \ + } \ + TINFL_GET_BYTE(state_index, c); \ + bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ + num_bits += 8; \ } while (num_bits < 15); -// TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read -// beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully -// decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. -// The slow path is only executed at the very end of the input buffer. -#define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \ - int temp; mz_uint code_len, c; \ - if (num_bits < 15) { \ - if ((pIn_buf_end - pIn_buf_cur) < 2) { \ - TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ - } else { \ - bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \ - } \ - } \ - if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ - code_len = temp >> 9, temp &= 511; \ - else { \ - code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \ - } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END +// TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex +// than you would initially expect because the zlib API expects the decompressor +// to never read beyond the final byte of the deflate stream. (In other words, +// when this macro wants to read another byte from the input, it REALLY needs +// another byte in order to fully decode the next Huffman code.) Handling this +// properly is particularly important on raw deflate (non-zlib) streams, which +// aren't followed by a byte aligned adler-32. The slow path is only executed at +// the very end of the input buffer. +#define TINFL_HUFF_DECODE(state_index, sym, pHuff) \ + do { \ + int temp; \ + mz_uint code_len, c; \ + if (num_bits < 15) { \ + if ((pIn_buf_end - pIn_buf_cur) < 2) { \ + TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ + } else { \ + bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | \ + (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \ + pIn_buf_cur += 2; \ + num_bits += 16; \ + } \ + } \ + if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= \ + 0) \ + code_len = temp >> 9, temp &= 511; \ + else { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do { \ + temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while (temp < 0); \ + } \ + sym = temp; \ + bit_buf >>= code_len; \ + num_bits -= code_len; \ + } \ + MZ_MACRO_END -tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) -{ - static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; - static const int s_length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; - static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; - static const int s_dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; - static const mz_uint8 s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; - static const int s_min_table_sizes[3] = { 257, 1, 4 }; +tinfl_status tinfl_decompress(tinfl_decompressor *r, + const mz_uint8 *pIn_buf_next, + size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, + mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, + const mz_uint32 decomp_flags) { + static const int s_length_base[31] = { + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; + static const int s_length_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, + 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, + 4, 4, 5, 5, 5, 5, 0, 0, 0}; + static const int s_dist_base[32] = { + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, + 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, + 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0}; + static const int s_dist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, + 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, + 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; + static const mz_uint8 s_length_dezigzag[19] = { + 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + static const int s_min_table_sizes[3] = {257, 1, 4}; - tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; - const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; - mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; - size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; + tinfl_status status = TINFL_STATUS_FAILED; + mz_uint32 num_bits, dist, counter, num_extra; + tinfl_bit_buf_t bit_buf; + const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = + pIn_buf_next + *pIn_buf_size; + mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = + pOut_buf_next + *pOut_buf_size; + size_t out_buf_size_mask = + (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) + ? (size_t)-1 + : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, + dist_from_out_buf_start; - // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). - if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } - - num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; - TINFL_CR_BEGIN - - bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; - if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) - { - TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); - counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); - if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); - if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } + // Ensure the output buffer's size is a power of 2, unless the output buffer + // is large enough to hold the entire output file (in which case it doesn't + // matter). + if (((out_buf_size_mask + 1) & out_buf_size_mask) || + (pOut_buf_next < pOut_buf_start)) { + *pIn_buf_size = *pOut_buf_size = 0; + return TINFL_STATUS_BAD_PARAM; } - do - { - TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; - if (r->m_type == 0) - { + num_bits = r->m_num_bits; + bit_buf = r->m_bit_buf; + dist = r->m_dist; + counter = r->m_counter; + num_extra = r->m_num_extra; + dist_from_out_buf_start = r->m_dist_from_out_buf_start; + TINFL_CR_BEGIN + + bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; + r->m_z_adler32 = r->m_check_adler32 = 1; + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { + TINFL_GET_BYTE(1, r->m_zhdr0); + TINFL_GET_BYTE(2, r->m_zhdr1); + counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || + (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); + if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || + ((out_buf_size_mask + 1) < + (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); + if (counter) { + TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); + } + } + + do { + TINFL_GET_BITS(3, r->m_final, 3); + r->m_type = r->m_final >> 1; + if (r->m_type == 0) { TINFL_SKIP_BITS(5, num_bits & 7); - for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } - if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } - while ((counter) && (num_bits)) - { + for (counter = 0; counter < 4; ++counter) { + if (num_bits) + TINFL_GET_BITS(6, r->m_raw_header[counter], 8); + else + TINFL_GET_BYTE(7, r->m_raw_header[counter]); + } + if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != + (mz_uint)(0xFFFF ^ + (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { + TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); + } + while ((counter) && (num_bits)) { TINFL_GET_BITS(51, dist, 8); - while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } + while (pOut_buf_cur >= pOut_buf_end) { + TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); + } *pOut_buf_cur++ = (mz_uint8)dist; counter--; } - while (counter) - { - size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } - while (pIn_buf_cur >= pIn_buf_end) - { - if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) - { + while (counter) { + size_t n; + while (pOut_buf_cur >= pOut_buf_end) { + TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); + } + while (pIn_buf_cur >= pIn_buf_end) { + if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT); - } - else - { + } else { TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); } } - n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); - TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; + n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), + (size_t)(pIn_buf_end - pIn_buf_cur)), + counter); + TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); + pIn_buf_cur += n; + pOut_buf_cur += n; + counter -= (mz_uint)n; } - } - else if (r->m_type == 3) - { + } else if (r->m_type == 3) { TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); - } - else - { - if (r->m_type == 1) - { - mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i; - r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); - for ( i = 0; i <= 143; ++i) *p++ = 8; for ( ; i <= 255; ++i) *p++ = 9; for ( ; i <= 279; ++i) *p++ = 7; for ( ; i <= 287; ++i) *p++ = 8; - } - else - { - for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } - MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; } + } else { + if (r->m_type == 1) { + mz_uint8 *p = r->m_tables[0].m_code_size; + mz_uint i; + r->m_table_sizes[0] = 288; + r->m_table_sizes[1] = 32; + TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); + for (i = 0; i <= 143; ++i) + *p++ = 8; + for (; i <= 255; ++i) + *p++ = 9; + for (; i <= 279; ++i) + *p++ = 7; + for (; i <= 287; ++i) + *p++ = 8; + } else { + for (counter = 0; counter < 3; counter++) { + TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); + r->m_table_sizes[counter] += s_min_table_sizes[counter]; + } + MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); + for (counter = 0; counter < r->m_table_sizes[2]; counter++) { + mz_uint s; + TINFL_GET_BITS(14, s, 3); + r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; + } r->m_table_sizes[2] = 19; } - for ( ; (int)r->m_type >= 0; r->m_type--) - { - int tree_next, tree_cur; tinfl_huff_table *pTable; - mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); - for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; - used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; - for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } - if ((65536 != total) && (used_syms > 1)) - { + for (; (int)r->m_type >= 0; r->m_type--) { + int tree_next, tree_cur; + tinfl_huff_table *pTable; + mz_uint i, j, used_syms, total, sym_index, next_code[17], + total_syms[16]; + pTable = &r->m_tables[r->m_type]; + MZ_CLEAR_OBJ(total_syms); + MZ_CLEAR_OBJ(pTable->m_look_up); + MZ_CLEAR_OBJ(pTable->m_tree); + for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) + total_syms[pTable->m_code_size[i]]++; + used_syms = 0, total = 0; + next_code[0] = next_code[1] = 0; + for (i = 1; i <= 15; ++i) { + used_syms += total_syms[i]; + next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); + } + if ((65536 != total) && (used_syms > 1)) { TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); } - for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) - { - mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; - cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); - if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } - if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } - rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); - for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) - { - tree_cur -= ((rev_code >>= 1) & 1); - if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; + for (tree_next = -1, sym_index = 0; + sym_index < r->m_table_sizes[r->m_type]; ++sym_index) { + mz_uint rev_code = 0, l, cur_code, + code_size = pTable->m_code_size[sym_index]; + if (!code_size) + continue; + cur_code = next_code[code_size]++; + for (l = code_size; l > 0; l--, cur_code >>= 1) + rev_code = (rev_code << 1) | (cur_code & 1); + if (code_size <= TINFL_FAST_LOOKUP_BITS) { + mz_int16 k = (mz_int16)((code_size << 9) | sym_index); + while (rev_code < TINFL_FAST_LOOKUP_SIZE) { + pTable->m_look_up[rev_code] = k; + rev_code += (1 << code_size); + } + continue; } - tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; + if (0 == + (tree_cur = pTable->m_look_up[rev_code & + (TINFL_FAST_LOOKUP_SIZE - 1)])) { + pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = + (mz_int16)tree_next; + tree_cur = tree_next; + tree_next -= 2; + } + rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); + for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) { + tree_cur -= ((rev_code >>= 1) & 1); + if (!pTable->m_tree[-tree_cur - 1]) { + pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; + tree_cur = tree_next; + tree_next -= 2; + } else + tree_cur = pTable->m_tree[-tree_cur - 1]; + } + tree_cur -= ((rev_code >>= 1) & 1); + pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; } - if (r->m_type == 2) - { - for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); ) - { - mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } - if ((dist == 16) && (!counter)) - { + if (r->m_type == 2) { + for (counter = 0; + counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) { + mz_uint s; + TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); + if (dist < 16) { + r->m_len_codes[counter++] = (mz_uint8)dist; + continue; + } + if ((dist == 16) && (!counter)) { TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); } - num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; - TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; + num_extra = "\02\03\07"[dist - 16]; + TINFL_GET_BITS(18, s, num_extra); + s += "\03\03\013"[dist - 16]; + TINFL_MEMSET(r->m_len_codes + counter, + (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); + counter += s; } - if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) - { + if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) { TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); } - TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); + TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, + r->m_table_sizes[0]); + TINFL_MEMCPY(r->m_tables[1].m_code_size, + r->m_len_codes + r->m_table_sizes[0], + r->m_table_sizes[1]); } } - for ( ; ; ) - { + for (;;) { mz_uint8 *pSrc; - for ( ; ; ) - { - if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) - { + for (;;) { + if (((pIn_buf_end - pIn_buf_cur) < 4) || + ((pOut_buf_end - pOut_buf_cur) < 2)) { TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); if (counter >= 256) break; - while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } - *pOut_buf_cur++ = (mz_uint8)counter; - } - else - { - int sym2; mz_uint code_len; -#if TINFL_USE_64BIT_BITBUF - if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } -#else - if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } -#endif - if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) - code_len = sym2 >> 9; - else - { - code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); + while (pOut_buf_cur >= pOut_buf_end) { + TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } - counter = sym2; bit_buf >>= code_len; num_bits -= code_len; + *pOut_buf_cur++ = (mz_uint8)counter; + } else { + int sym2; + mz_uint code_len; +#if TINFL_USE_64BIT_BITBUF + if (num_bits < 30) { + bit_buf |= + (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 4; + num_bits += 32; + } +#else + if (num_bits < 15) { + bit_buf |= + (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 2; + num_bits += 16; + } +#endif + if ((sym2 = + r->m_tables[0] + .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= + 0) + code_len = sym2 >> 9; + else { + code_len = TINFL_FAST_LOOKUP_BITS; + do { + sym2 = r->m_tables[0] + .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; + } while (sym2 < 0); + } + counter = sym2; + bit_buf >>= code_len; + num_bits -= code_len; if (counter & 256) break; #if !TINFL_USE_64BIT_BITBUF - if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } -#endif - if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) - code_len = sym2 >> 9; - else - { - code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); + if (num_bits < 15) { + bit_buf |= + (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 2; + num_bits += 16; } - bit_buf >>= code_len; num_bits -= code_len; +#endif + if ((sym2 = + r->m_tables[0] + .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= + 0) + code_len = sym2 >> 9; + else { + code_len = TINFL_FAST_LOOKUP_BITS; + do { + sym2 = r->m_tables[0] + .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; + } while (sym2 < 0); + } + bit_buf >>= code_len; + num_bits -= code_len; pOut_buf_cur[0] = (mz_uint8)counter; - if (sym2 & 256) - { + if (sym2 & 256) { pOut_buf_cur++; counter = sym2; break; @@ -1610,46 +2243,56 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex pOut_buf_cur += 2; } } - if ((counter &= 511) == 256) break; + if ((counter &= 511) == 256) + break; - num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; - if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } + num_extra = s_length_extra[counter - 257]; + counter = s_length_base[counter - 257]; + if (num_extra) { + mz_uint extra_bits; + TINFL_GET_BITS(25, extra_bits, num_extra); + counter += extra_bits; + } TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); - num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; - if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } + num_extra = s_dist_extra[dist]; + dist = s_dist_base[dist]; + if (num_extra) { + mz_uint extra_bits; + TINFL_GET_BITS(27, extra_bits, num_extra); + dist += extra_bits; + } dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; - if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) - { + if ((dist > dist_from_out_buf_start) && + (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) { TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); } - pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); + pSrc = pOut_buf_start + + ((dist_from_out_buf_start - dist) & out_buf_size_mask); - if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) - { - while (counter--) - { - while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } - *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; + if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) { + while (counter--) { + while (pOut_buf_cur >= pOut_buf_end) { + TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = + pOut_buf_start[(dist_from_out_buf_start++ - dist) & + out_buf_size_mask]; } continue; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES - else if ((counter >= 9) && (counter <= dist)) - { + else if ((counter >= 9) && (counter <= dist)) { const mz_uint8 *pSrc_end = pSrc + (counter & ~7); - do - { + do { ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; pOut_buf_cur += 8; } while ((pSrc += 8) < pSrc_end); - if ((counter &= 7) < 3) - { - if (counter) - { + if ((counter &= 7) < 3) { + if (counter) { pOut_buf_cur[0] = pSrc[0]; if (counter > 1) pOut_buf_cur[1] = pSrc[1]; @@ -1659,15 +2302,14 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex } } #endif - do - { + do { pOut_buf_cur[0] = pSrc[0]; pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur[2] = pSrc[2]; - pOut_buf_cur += 3; pSrc += 3; + pOut_buf_cur += 3; + pSrc += 3; } while ((int)(counter -= 3) > 2); - if ((int)counter > 0) - { + if ((int)counter > 0) { pOut_buf_cur[0] = pSrc[0]; if ((int)counter > 1) pOut_buf_cur[1] = pSrc[1]; @@ -1676,89 +2318,142 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex } } } while (!(r->m_final & 1)); - if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) - { - TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { + TINFL_SKIP_BITS(32, num_bits & 7); + for (counter = 0; counter < 4; ++counter) { + mz_uint s; + if (num_bits) + TINFL_GET_BITS(41, s, 8); + else + TINFL_GET_BYTE(42, s); + r->m_z_adler32 = (r->m_z_adler32 << 8) | s; + } } TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); TINFL_CR_FINISH common_exit: - r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; - *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; - if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) - { - const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; - mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; - while (buf_len) - { - for (i = 0; i + 7 < block_len; i += 8, ptr += 8) - { - s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; - s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; + r->m_num_bits = num_bits; + r->m_bit_buf = bit_buf; + r->m_dist = dist; + r->m_counter = counter; + r->m_num_extra = num_extra; + r->m_dist_from_out_buf_start = dist_from_out_buf_start; + *pIn_buf_size = pIn_buf_cur - pIn_buf_next; + *pOut_buf_size = pOut_buf_cur - pOut_buf_next; + if ((decomp_flags & + (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && + (status >= 0)) { + const mz_uint8 *ptr = pOut_buf_next; + size_t buf_len = *pOut_buf_size; + mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, + s2 = r->m_check_adler32 >> 16; + size_t block_len = buf_len % 5552; + while (buf_len) { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { + s1 += ptr[0], s2 += s1; + s1 += ptr[1], s2 += s1; + s1 += ptr[2], s2 += s1; + s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; + s1 += ptr[5], s2 += s1; + s1 += ptr[6], s2 += s1; + s1 += ptr[7], s2 += s1; } - for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; - s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; + for (; i < block_len; ++i) + s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; + buf_len -= block_len; + block_len = 5552; } - r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; + r->m_check_adler32 = (s2 << 16) + s1; + if ((status == TINFL_STATUS_DONE) && + (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && + (r->m_check_adler32 != r->m_z_adler32)) + status = TINFL_STATUS_ADLER32_MISMATCH; } return status; } // Higher level helper functions. -void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) -{ - tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, + size_t *pOut_len, int flags) { + tinfl_decompressor decomp; + void *pBuf = NULL, *pNew_buf; + size_t src_buf_ofs = 0, out_buf_capacity = 0; *pOut_len = 0; tinfl_init(&decomp); - for ( ; ; ) - { - size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; - tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8*)pBuf, pBuf ? (mz_uint8*)pBuf + *pOut_len : NULL, &dst_buf_size, - (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); - if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) - { - MZ_FREE(pBuf); *pOut_len = 0; return NULL; + for (;;) { + size_t src_buf_size = src_buf_len - src_buf_ofs, + dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; + tinfl_status status = tinfl_decompress( + &decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, + (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, + &dst_buf_size, + (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) { + MZ_FREE(pBuf); + *pOut_len = 0; + return NULL; } src_buf_ofs += src_buf_size; *pOut_len += dst_buf_size; - if (status == TINFL_STATUS_DONE) break; - new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; + if (status == TINFL_STATUS_DONE) + break; + new_out_buf_capacity = out_buf_capacity * 2; + if (new_out_buf_capacity < 128) + new_out_buf_capacity = 128; pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); - if (!pNew_buf) - { - MZ_FREE(pBuf); *pOut_len = 0; return NULL; + if (!pNew_buf) { + MZ_FREE(pBuf); + *pOut_len = 0; + return NULL; } - pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; + pBuf = pNew_buf; + out_buf_capacity = new_out_buf_capacity; } return pBuf; } -size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) -{ - tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp); - status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); - return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, + const void *pSrc_buf, size_t src_buf_len, + int flags) { + tinfl_decompressor decomp; + tinfl_status status; + tinfl_init(&decomp); + status = + tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, + (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, + (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED + : out_buf_len; } -int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) -{ +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, + tinfl_put_buf_func_ptr pPut_buf_func, + void *pPut_buf_user, int flags) { int result = 0; tinfl_decompressor decomp; - mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; + mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); + size_t in_buf_ofs = 0, dict_ofs = 0; if (!pDict) return TINFL_STATUS_FAILED; tinfl_init(&decomp); - for ( ; ; ) - { - size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; - tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, - (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); + for (;;) { + size_t in_buf_size = *pIn_buf_size - in_buf_ofs, + dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; + tinfl_status status = + tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, + &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, + (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); in_buf_ofs += in_buf_size; - if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) + if ((dst_buf_size) && + (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) break; - if (status != TINFL_STATUS_HAS_MORE_OUTPUT) - { + if (status != TINFL_STATUS_HAS_MORE_OUTPUT) { result = (status == TINFL_STATUS_DONE); break; } @@ -1769,220 +2464,390 @@ int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, return result; } -// ------------------- Low-level Compression (independent from all decompression API's) +// ------------------- Low-level Compression (independent from all decompression +// API's) // Purposely making these tables static for faster init and thread safety. static const mz_uint16 s_tdefl_len_sym[256] = { - 257,258,259,260,261,262,263,264,265,265,266,266,267,267,268,268,269,269,269,269,270,270,270,270,271,271,271,271,272,272,272,272, - 273,273,273,273,273,273,273,273,274,274,274,274,274,274,274,274,275,275,275,275,275,275,275,275,276,276,276,276,276,276,276,276, - 277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278, - 279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280, - 281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281, - 282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282, - 283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283, - 284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,285 }; + 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, + 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, + 272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, + 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, + 276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, + 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, + 278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279, + 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, + 280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281, + 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, + 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282, + 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, + 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283, + 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, + 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284, + 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, + 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, + 285}; static const mz_uint8 s_tdefl_len_extra[256] = { - 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, - 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, - 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, - 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,0 }; + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0}; static const mz_uint8 s_tdefl_small_dist_sym[512] = { - 0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11, - 11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13, - 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14, - 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14, - 14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15, - 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16, - 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, - 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, - 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17, - 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, - 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, - 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17 }; + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, + 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, + 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, + 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, + 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, + 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17}; static const mz_uint8 s_tdefl_small_dist_extra[512] = { - 0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5, - 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, - 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, - 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 7,7,7,7,7,7,7,7 }; + 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}; static const mz_uint8 s_tdefl_large_dist_sym[128] = { - 0,0,18,19,20,20,21,21,22,22,22,22,23,23,23,23,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26, - 26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28, - 28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29 }; + 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, + 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, + 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, + 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29}; static const mz_uint8 s_tdefl_large_dist_extra[128] = { - 0,0,8,8,9,9,9,9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12, - 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13, - 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13 }; + 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, + 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, + 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, + 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13}; -// Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. -typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq; -static tdefl_sym_freq* tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq* pSyms0, tdefl_sym_freq* pSyms1) -{ - mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist); - for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } - while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--; - for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) - { - const mz_uint32* pHist = &hist[pass << 8]; +// Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted +// values. +typedef struct { + mz_uint16 m_key, m_sym_index; +} tdefl_sym_freq; +static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, + tdefl_sym_freq *pSyms0, + tdefl_sym_freq *pSyms1) { + mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; + tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; + MZ_CLEAR_OBJ(hist); + for (i = 0; i < num_syms; i++) { + mz_uint freq = pSyms0[i].m_key; + hist[freq & 0xFF]++; + hist[256 + ((freq >> 8) & 0xFF)]++; + } + while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) + total_passes--; + for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) { + const mz_uint32 *pHist = &hist[pass << 8]; mz_uint offsets[256], cur_ofs = 0; - for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } - for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; - { tdefl_sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } + for (i = 0; i < 256; i++) { + offsets[i] = cur_ofs; + cur_ofs += pHist[i]; + } + for (i = 0; i < num_syms; i++) + pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = + pCur_syms[i]; + { + tdefl_sym_freq *t = pCur_syms; + pCur_syms = pNew_syms; + pNew_syms = t; + } } return pCur_syms; } -// tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. -static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) -{ +// tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, +// alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. +static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) { int root, leaf, next, avbl, used, dpth; - if (n==0) return; else if (n==1) { A[0].m_key = 1; return; } - A[0].m_key += A[1].m_key; root = 0; leaf = 2; - for (next=1; next < n-1; next++) - { - if (leaf>=n || A[root].m_key=n || (root=0; next--) A[next].m_key = A[A[next].m_key].m_key+1; - avbl = 1; used = dpth = 0; root = n-2; next = n-1; - while (avbl>0) - { - while (root>=0 && (int)A[root].m_key==dpth) { used++; root--; } - while (avbl>used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; } - avbl = 2*used; dpth++; used = 0; + A[0].m_key += A[1].m_key; + root = 0; + leaf = 2; + for (next = 1; next < n - 1; next++) { + if (leaf >= n || A[root].m_key < A[leaf].m_key) { + A[next].m_key = A[root].m_key; + A[root++].m_key = (mz_uint16)next; + } else + A[next].m_key = A[leaf++].m_key; + if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) { + A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); + A[root++].m_key = (mz_uint16)next; + } else + A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); + } + A[n - 2].m_key = 0; + for (next = n - 3; next >= 0; next--) + A[next].m_key = A[A[next].m_key].m_key + 1; + avbl = 1; + used = dpth = 0; + root = n - 2; + next = n - 1; + while (avbl > 0) { + while (root >= 0 && (int)A[root].m_key == dpth) { + used++; + root--; + } + while (avbl > used) { + A[next--].m_key = (mz_uint16)(dpth); + avbl--; + } + avbl = 2 * used; + dpth++; + used = 0; } } // Limits canonical Huffman code table's max code size. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; -static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) -{ - int i; mz_uint32 total = 0; if (code_list_len <= 1) return; - for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i]; - for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); - while (total != (1UL << max_code_size)) - { +static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, + int code_list_len, + int max_code_size) { + int i; + mz_uint32 total = 0; + if (code_list_len <= 1) + return; + for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) + pNum_codes[max_code_size] += pNum_codes[i]; + for (i = max_code_size; i > 0; i--) + total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); + while (total != (1UL << max_code_size)) { pNum_codes[max_code_size]--; - for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; } + for (i = max_code_size - 1; i > 0; i--) + if (pNum_codes[i]) { + pNum_codes[i]--; + pNum_codes[i + 1] += 2; + break; + } total--; } } -static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) -{ - int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes); - if (static_table) - { - for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++; - } - else - { - tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; +static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, + int table_len, int code_size_limit, + int static_table) { + int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; + mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; + MZ_CLEAR_OBJ(num_codes); + if (static_table) { + for (i = 0; i < table_len; i++) + num_codes[d->m_huff_code_sizes[table_num][i]]++; + } else { + tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], + *pSyms; int num_used_syms = 0; const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; - for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; } + for (i = 0; i < table_len; i++) + if (pSym_count[i]) { + syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; + syms0[num_used_syms++].m_sym_index = (mz_uint16)i; + } - pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); + pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); + tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); - for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++; + for (i = 0; i < num_used_syms; i++) + num_codes[pSyms[i].m_key]++; - tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); + tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, + code_size_limit); - MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); + MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); + MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); for (i = 1, j = num_used_syms; i <= code_size_limit; i++) - for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); + for (l = num_codes[i]; l > 0; l--) + d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); } - next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1); + next_code[1] = 0; + for (j = 0, i = 2; i <= code_size_limit; i++) + next_code[i] = j = ((j + num_codes[i - 1]) << 1); - for (i = 0; i < table_len; i++) - { - mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue; - code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1); + for (i = 0; i < table_len; i++) { + mz_uint rev_code = 0, code, code_size; + if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) + continue; + code = next_code[code_size]++; + for (l = code_size; l > 0; l--, code >>= 1) + rev_code = (rev_code << 1) | (code & 1); d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; } } -#define TDEFL_PUT_BITS(b, l) do { \ - mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \ - d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \ - while (d->m_bits_in >= 8) { \ - if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ - *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ - d->m_bit_buffer >>= 8; \ - d->m_bits_in -= 8; \ - } \ -} MZ_MACRO_END +#define TDEFL_PUT_BITS(b, l) \ + do { \ + mz_uint bits = b; \ + mz_uint len = l; \ + MZ_ASSERT(bits <= ((1U << len) - 1U)); \ + d->m_bit_buffer |= (bits << d->m_bits_in); \ + d->m_bits_in += len; \ + while (d->m_bits_in >= 8) { \ + if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ + *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ + d->m_bit_buffer >>= 8; \ + d->m_bits_in -= 8; \ + } \ + } \ + MZ_MACRO_END -#define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \ - if (rle_repeat_count < 3) { \ - d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ - while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ - } else { \ - d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \ -} rle_repeat_count = 0; } } +#define TDEFL_RLE_PREV_CODE_SIZE() \ + { \ + if (rle_repeat_count) { \ + if (rle_repeat_count < 3) { \ + d->m_huff_count[2][prev_code_size] = (mz_uint16)( \ + d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ + while (rle_repeat_count--) \ + packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ + } else { \ + d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 16; \ + packed_code_sizes[num_packed_code_sizes++] = \ + (mz_uint8)(rle_repeat_count - 3); \ + } \ + rle_repeat_count = 0; \ + } \ + } -#define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \ - if (rle_z_count < 3) { \ - d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ - } else if (rle_z_count <= 10) { \ - d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \ - } else { \ - d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \ -} rle_z_count = 0; } } +#define TDEFL_RLE_ZERO_CODE_SIZE() \ + { \ + if (rle_z_count) { \ + if (rle_z_count < 3) { \ + d->m_huff_count[2][0] = \ + (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \ + while (rle_z_count--) \ + packed_code_sizes[num_packed_code_sizes++] = 0; \ + } else if (rle_z_count <= 10) { \ + d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 17; \ + packed_code_sizes[num_packed_code_sizes++] = \ + (mz_uint8)(rle_z_count - 3); \ + } else { \ + d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 18; \ + packed_code_sizes[num_packed_code_sizes++] = \ + (mz_uint8)(rle_z_count - 11); \ + } \ + rle_z_count = 0; \ + } \ + } -static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; +static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { + 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; -static void tdefl_start_dynamic_block(tdefl_compressor *d) -{ - int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; - mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; +static void tdefl_start_dynamic_block(tdefl_compressor *d) { + int num_lit_codes, num_dist_codes, num_bit_lengths; + mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, + rle_repeat_count, packed_code_sizes_index; + mz_uint8 + code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], + packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], + prev_code_size = 0xFF; d->m_huff_count[0][256] = 1; tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); - for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break; - for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break; + for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) + if (d->m_huff_code_sizes[0][num_lit_codes - 1]) + break; + for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) + if (d->m_huff_code_sizes[1][num_dist_codes - 1]) + break; - memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); - memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); - total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0; + memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], + sizeof(mz_uint8) * num_lit_codes); + memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], + sizeof(mz_uint8) * num_dist_codes); + total_code_sizes_to_pack = num_lit_codes + num_dist_codes; + num_packed_code_sizes = 0; + rle_z_count = 0; + rle_repeat_count = 0; - memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); - for (i = 0; i < total_code_sizes_to_pack; i++) - { + memset(&d->m_huff_count[2][0], 0, + sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); + for (i = 0; i < total_code_sizes_to_pack; i++) { mz_uint8 code_size = code_sizes_to_pack[i]; - if (!code_size) - { + if (!code_size) { TDEFL_RLE_PREV_CODE_SIZE(); - if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); } - } - else - { - TDEFL_RLE_ZERO_CODE_SIZE(); - if (code_size != prev_code_size) - { - TDEFL_RLE_PREV_CODE_SIZE(); - d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; + if (++rle_z_count == 138) { + TDEFL_RLE_ZERO_CODE_SIZE(); } - else if (++rle_repeat_count == 6) - { + } else { + TDEFL_RLE_ZERO_CODE_SIZE(); + if (code_size != prev_code_size) { + TDEFL_RLE_PREV_CODE_SIZE(); + d->m_huff_count[2][code_size] = + (mz_uint16)(d->m_huff_count[2][code_size] + 1); + packed_code_sizes[num_packed_code_sizes++] = code_size; + } else if (++rle_repeat_count == 6) { TDEFL_RLE_PREV_CODE_SIZE(); } } prev_code_size = code_size; } - if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); } + if (rle_repeat_count) { + TDEFL_RLE_PREV_CODE_SIZE(); + } else { + TDEFL_RLE_ZERO_CODE_SIZE(); + } tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); @@ -1991,27 +2856,39 @@ static void tdefl_start_dynamic_block(tdefl_compressor *d) TDEFL_PUT_BITS(num_lit_codes - 257, 5); TDEFL_PUT_BITS(num_dist_codes - 1, 5); - for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break; - num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4); - for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); + for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) + if (d->m_huff_code_sizes + [2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) + break; + num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); + TDEFL_PUT_BITS(num_bit_lengths - 4, 4); + for (i = 0; (int)i < num_bit_lengths; i++) + TDEFL_PUT_BITS( + d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); - for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes; ) - { - mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); + for (packed_code_sizes_index = 0; + packed_code_sizes_index < num_packed_code_sizes;) { + mz_uint code = packed_code_sizes[packed_code_sizes_index++]; + MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); - if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); + if (code >= 16) + TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], + "\02\03\07"[code - 16]); } } -static void tdefl_start_static_block(tdefl_compressor *d) -{ +static void tdefl_start_static_block(tdefl_compressor *d) { mz_uint i; mz_uint8 *p = &d->m_huff_code_sizes[0][0]; - for (i = 0; i <= 143; ++i) *p++ = 8; - for ( ; i <= 255; ++i) *p++ = 9; - for ( ; i <= 279; ++i) *p++ = 7; - for ( ; i <= 287; ++i) *p++ = 8; + for (i = 0; i <= 143; ++i) + *p++ = 8; + for (; i <= 255; ++i) + *p++ = 9; + for (; i <= 279; ++i) + *p++ = 7; + for (; i <= 287; ++i) + *p++ = 8; memset(d->m_huff_code_sizes[1], 5, 32); @@ -2021,11 +2898,13 @@ static void tdefl_start_static_block(tdefl_compressor *d) TDEFL_PUT_BITS(1, 2); } -static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; +static const mz_uint mz_bitmasks[17] = { + 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, + 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF}; -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS -static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) -{ +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \ + MINIZ_HAS_64BIT_REGISTERS +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; mz_uint8 *pOutput_buf = d->m_pOutput_buf; @@ -2033,22 +2912,29 @@ static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) mz_uint64 bit_buffer = d->m_bit_buffer; mz_uint bits_in = d->m_bits_in; -#define TDEFL_PUT_BITS_FAST(b, l) { bit_buffer |= (((mz_uint64)(b)) << bits_in); bits_in += (l); } +#define TDEFL_PUT_BITS_FAST(b, l) \ + { \ + bit_buffer |= (((mz_uint64)(b)) << bits_in); \ + bits_in += (l); \ + } flags = 1; - for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) - { + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; + flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; - if (flags & 1) - { + if (flags & 1) { mz_uint s0, s1, n0, n1, sym, num_extra_bits; - mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3; + mz_uint match_len = pLZ_codes[0], + match_dist = *(const mz_uint16 *)(pLZ_codes + 1); + pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); - TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], + d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], + s_tdefl_len_extra[match_len]); // This sequence coaxes MSVC into using cmov's vs. jmp's. s0 = s_tdefl_small_dist_sym[match_dist & 511]; @@ -2059,28 +2945,29 @@ static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) num_extra_bits = (match_dist < 512) ? n0 : n1; MZ_ASSERT(d->m_huff_code_sizes[1][sym]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); - TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); - } - else - { + TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], + d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], + num_extra_bits); + } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], + d->m_huff_code_sizes[0][lit]); - if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) - { + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], + d->m_huff_code_sizes[0][lit]); - if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) - { + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], + d->m_huff_code_sizes[0][lit]); } } } @@ -2088,7 +2975,7 @@ static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) if (pOutput_buf >= d->m_pOutput_buf_end) return MZ_FALSE; - *(mz_uint64*)pOutput_buf = bit_buffer; + *(mz_uint64 *)pOutput_buf = bit_buffer; pOutput_buf += (bits_in >> 3); bit_buffer >>= (bits_in & ~7); bits_in &= 7; @@ -2100,8 +2987,7 @@ static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) d->m_bits_in = 0; d->m_bit_buffer = 0; - while (bits_in) - { + while (bits_in) { mz_uint32 n = MZ_MIN(bits_in, 16); TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); bit_buffer >>= n; @@ -2113,39 +2999,37 @@ static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #else -static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) -{ +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; flags = 1; - for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) - { + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; + flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; - if (flags & 1) - { + if (flags & 1) { mz_uint sym, num_extra_bits; - mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3; + mz_uint match_len = pLZ_codes[0], + match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); + pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); - TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); - TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], + d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], + s_tdefl_len_extra[match_len]); - if (match_dist < 512) - { - sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist]; + if (match_dist < 512) { + sym = s_tdefl_small_dist_sym[match_dist]; + num_extra_bits = s_tdefl_small_dist_extra[match_dist]; + } else { + sym = s_tdefl_large_dist_sym[match_dist >> 8]; + num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; } - else - { - sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; - } - MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); - } - else - { + } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); @@ -2156,10 +3040,10 @@ static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) return (d->m_pOutput_buf < d->m_pOutput_buf_end); } -#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS +#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && + // MINIZ_HAS_64BIT_REGISTERS -static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) -{ +static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) { if (static_block) tdefl_start_static_block(d); else @@ -2167,13 +3051,18 @@ static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) return tdefl_compress_lz_codes(d); } -static int tdefl_flush_block(tdefl_compressor *d, int flush) -{ +static int tdefl_flush_block(tdefl_compressor *d, int flush) { mz_uint saved_bit_buf, saved_bits_in; mz_uint8 *pSaved_output_buf; mz_bool comp_block_succeeded = MZ_FALSE; - int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; - mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; + int n, use_raw_block = + ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && + (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; + mz_uint8 *pOutput_buf_start = + ((d->m_pPut_buf_func == NULL) && + ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) + ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) + : d->m_output_buf; d->m_pOutput_buf = pOutput_buf_start; d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; @@ -2185,82 +3074,106 @@ static int tdefl_flush_block(tdefl_compressor *d, int flush) *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); - if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) - { - TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8); + if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) { + TDEFL_PUT_BITS(0x78, 8); + TDEFL_PUT_BITS(0x01, 8); } TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); - pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; + pSaved_output_buf = d->m_pOutput_buf; + saved_bit_buf = d->m_bit_buffer; + saved_bits_in = d->m_bits_in; if (!use_raw_block) - comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); + comp_block_succeeded = + tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || + (d->m_total_lz_bytes < 48)); - // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. - if ( ((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && - ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size) ) - { - mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + // If the block gets expanded, forget the current contents of the output + // buffer and send a raw block instead. + if (((use_raw_block) || + ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= + d->m_total_lz_bytes))) && + ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) { + mz_uint i; + d->m_pOutput_buf = pSaved_output_buf; + d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; TDEFL_PUT_BITS(0, 2); - if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } - for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) - { + if (d->m_bits_in) { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) { TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); } - for (i = 0; i < d->m_total_lz_bytes; ++i) - { - TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); + for (i = 0; i < d->m_total_lz_bytes; ++i) { + TDEFL_PUT_BITS( + d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], + 8); } } - // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. - else if (!comp_block_succeeded) - { - d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + // Check for the extremely unlikely (if not impossible) case of the compressed + // block not fitting into the output buffer when using dynamic codes. + else if (!comp_block_succeeded) { + d->m_pOutput_buf = pSaved_output_buf; + d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; tdefl_compress_block(d, MZ_TRUE); } - if (flush) - { - if (flush == TDEFL_FINISH) - { - if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } - if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } } - } - else - { - mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); } + if (flush) { + if (flush == TDEFL_FINISH) { + if (d->m_bits_in) { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { + mz_uint i, a = d->m_adler32; + for (i = 0; i < 4; i++) { + TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); + a <<= 8; + } + } + } else { + mz_uint i, z = 0; + TDEFL_PUT_BITS(0, 3); + if (d->m_bits_in) { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + for (i = 2; i; --i, z ^= 0xFFFF) { + TDEFL_PUT_BITS(z & 0xFFFF, 16); + } } } MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); - memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); - memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + memset(&d->m_huff_count[0][0], 0, + sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, + sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); - d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++; + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; + d->m_pLZ_flags = d->m_lz_code_buf; + d->m_num_flags_left = 8; + d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; + d->m_total_lz_bytes = 0; + d->m_block_index++; - if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) - { - if (d->m_pPut_buf_func) - { + if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) { + if (d->m_pPut_buf_func) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); - } - else if (pOutput_buf_start == d->m_output_buf) - { - int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); - memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); + } else if (pOutput_buf_start == d->m_output_buf) { + int bytes_to_copy = (int)MZ_MIN( + (size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, + bytes_to_copy); d->m_out_buf_ofs += bytes_to_copy; - if ((n -= bytes_to_copy) != 0) - { + if ((n -= bytes_to_copy) != 0) { d->m_output_flush_ofs = bytes_to_copy; d->m_output_flush_remaining = n; } - } - else - { + } else { d->m_out_buf_ofs += n; } } @@ -2269,133 +3182,192 @@ static int tdefl_flush_block(tdefl_compressor *d, int flush) } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES -#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16*)(p) -static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) -{ - mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; +#define TDEFL_READ_UNALIGNED_WORD(p) ((p)[0] | (p)[1] << 8) +static MZ_FORCEINLINE void +tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, + mz_uint max_match_len, mz_uint *pMatch_dist, + mz_uint *pMatch_len) { + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, + match_len = *pMatch_len, probe_pos = pos, next_probe_pos, + probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; - const mz_uint16 *s = (const mz_uint16*)(d->m_dict + pos), *p, *q; - mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s); - MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; - for ( ; ; ) - { - for ( ; ; ) - { - if (--num_probes_left == 0) return; - #define TDEFL_PROBE \ - next_probe_pos = d->m_next[probe_pos]; \ - if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ - probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ - if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) break; - TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; + const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q; + mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), + s01 = *s; + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); + if (max_match_len <= match_len) + return; + for (;;) { + for (;;) { + if (--num_probes_left == 0) + return; +#define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || \ + ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ + return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ + break; + TDEFL_PROBE; + TDEFL_PROBE; + TDEFL_PROBE; } - if (!dist) break; q = (const mz_uint16*)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue; p = s; probe_len = 32; - do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && - (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) ); - if (!probe_len) - { - *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break; - } - else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8*)p == *(const mz_uint8*)q)) > match_len) - { - *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break; + if (!dist) + break; + q = (const mz_uint16 *)(d->m_dict + probe_pos); + if (*q != s01) + continue; + p = s; + probe_len = 32; + do { + } while ((*(++p) == *(++q)) && (*(++p) == *(++q)) && (*(++p) == *(++q)) && + (*(++p) == *(++q)) && (--probe_len > 0)); + if (!probe_len) { + *pMatch_dist = dist; + *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); + break; + } else if ((probe_len = ((mz_uint)(p - s) * 2) + + (mz_uint)(*(const mz_uint8 *)p == + *(const mz_uint8 *)q)) > match_len) { + *pMatch_dist = dist; + if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == + max_match_len) + break; c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); } } } #else -static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) -{ - mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; +static MZ_FORCEINLINE void +tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, + mz_uint max_match_len, mz_uint *pMatch_dist, + mz_uint *pMatch_len) { + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, + match_len = *pMatch_len, probe_pos = pos, next_probe_pos, + probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint8 *s = d->m_dict + pos, *p, *q; mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; - MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; - for ( ; ; ) - { - for ( ; ; ) - { - if (--num_probes_left == 0) return; - #define TDEFL_PROBE \ - next_probe_pos = d->m_next[probe_pos]; \ - if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ - probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ - if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break; - TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); + if (max_match_len <= match_len) + return; + for (;;) { + for (;;) { + if (--num_probes_left == 0) + return; +#define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || \ + ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ + return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if ((d->m_dict[probe_pos + match_len] == c0) && \ + (d->m_dict[probe_pos + match_len - 1] == c1)) \ + break; + TDEFL_PROBE; + TDEFL_PROBE; + TDEFL_PROBE; } - if (!dist) break; p = s; q = d->m_dict + probe_pos; for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break; - if (probe_len > match_len) - { - *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return; - c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1]; + if (!dist) + break; + p = s; + q = d->m_dict + probe_pos; + for (probe_len = 0; probe_len < max_match_len; probe_len++) + if (*p++ != *q++) + break; + if (probe_len > match_len) { + *pMatch_dist = dist; + if ((*pMatch_len = match_len = probe_len) == max_match_len) + return; + c0 = d->m_dict[pos + match_len]; + c1 = d->m_dict[pos + match_len - 1]; } } } #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN -static mz_bool tdefl_compress_fast(tdefl_compressor *d) -{ - // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. - mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; +static mz_bool tdefl_compress_fast(tdefl_compressor *d) { + // Faster, minimally featured LZRW1-style match+parse loop with better + // register utilization. Intended for applications where raw throughput is + // valued more highly than ratio. + mz_uint lookahead_pos = d->m_lookahead_pos, + lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, + total_lz_bytes = d->m_total_lz_bytes, + num_flags_left = d->m_num_flags_left; mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; - while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) - { + while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) { const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; - mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; - mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); + mz_uint dst_pos = + (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( + d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); d->m_src_buf_left -= num_bytes_to_process; lookahead_size += num_bytes_to_process; - while (num_bytes_to_process) - { + while (num_bytes_to_process) { mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); memcpy(d->m_dict + dst_pos, d->m_pSrc, n); if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) - memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); + memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, + MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); d->m_pSrc += n; dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; num_bytes_to_process -= n; } dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); - if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break; + if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) + break; - while (lookahead_size >= 4) - { + while (lookahead_size >= 4) { mz_uint cur_match_dist, cur_match_len = 1; mz_uint8 *pCur_dict = d->m_dict + cur_pos; mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF; - mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; + mz_uint hash = + (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & + TDEFL_LEVEL1_HASH_SIZE_MASK; mz_uint probe_pos = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)lookahead_pos; - if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) - { + if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= + dict_size) && + ((mz_uint32)( + *(d->m_dict + (probe_pos & TDEFL_LZ_DICT_SIZE_MASK)) | + (*(d->m_dict + ((probe_pos & TDEFL_LZ_DICT_SIZE_MASK) + 1)) + << 8) | + (*(d->m_dict + ((probe_pos & TDEFL_LZ_DICT_SIZE_MASK) + 2)) + << 16)) == first_trigram)) { const mz_uint16 *p = (const mz_uint16 *)pCur_dict; - const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); + const mz_uint16 *q = + (const mz_uint16 *)(d->m_dict + + (probe_pos & TDEFL_LZ_DICT_SIZE_MASK)); mz_uint32 probe_len = 32; - do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && - (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) ); - cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); + do { + } while ((*(++p) == *(++q)) && (*(++p) == *(++q)) && + (*(++p) == *(++q)) && (*(++p) == *(++q)) && (--probe_len > 0)); + cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); if (!probe_len) cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; - if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U))) - { + if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || + ((cur_match_len == TDEFL_MIN_MATCH_LEN) && + (cur_match_dist >= 8U * 1024U))) { cur_match_len = 1; *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; - } - else - { + } else { mz_uint32 s0, s1; cur_match_len = MZ_MIN(cur_match_len, lookahead_size); - MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); + MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && + (cur_match_dist >= 1) && + (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); cur_match_dist--; @@ -2408,17 +3380,19 @@ static mz_bool tdefl_compress_fast(tdefl_compressor *d) s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; - d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; + d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - + TDEFL_MIN_MATCH_LEN]]++; } - } - else - { + } else { *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } - if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } + if (--num_flags_left == 0) { + num_flags_left = 8; + pLZ_flags = pLZ_code_buf++; + } total_lz_bytes += cur_match_len; lookahead_pos += cur_match_len; @@ -2427,25 +3401,34 @@ static mz_bool tdefl_compress_fast(tdefl_compressor *d) MZ_ASSERT(lookahead_size >= cur_match_len); lookahead_size -= cur_match_len; - if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) - { + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; - d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; - d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; - total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; + total_lz_bytes = d->m_total_lz_bytes; + pLZ_code_buf = d->m_pLZ_code_buf; + pLZ_flags = d->m_pLZ_flags; + num_flags_left = d->m_num_flags_left; } } - while (lookahead_size) - { + while (lookahead_size) { mz_uint8 lit = d->m_dict[cur_pos]; total_lz_bytes++; *pLZ_code_buf++ = lit; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); - if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } + if (--num_flags_left == 0) { + num_flags_left = 8; + pLZ_flags = pLZ_code_buf++; + } d->m_huff_count[0][lit]++; @@ -2454,37 +3437,54 @@ static mz_bool tdefl_compress_fast(tdefl_compressor *d) cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; lookahead_size--; - if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) - { + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; - d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; - d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; - total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; + total_lz_bytes = d->m_total_lz_bytes; + pLZ_code_buf = d->m_pLZ_code_buf; + pLZ_flags = d->m_pLZ_flags; + num_flags_left = d->m_num_flags_left; } } } - d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; - d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; return MZ_TRUE; } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN -static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) -{ +static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, + mz_uint8 lit) { d->m_total_lz_bytes++; *d->m_pLZ_code_buf++ = lit; - *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); + if (--d->m_num_flags_left == 0) { + d->m_num_flags_left = 8; + d->m_pLZ_flags = d->m_pLZ_code_buf++; + } d->m_huff_count[0][lit]++; } -static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) -{ +static MZ_FORCEINLINE void +tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) { mz_uint32 s0, s1; - MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); + MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && + (match_dist <= TDEFL_LZ_DICT_SIZE)); d->m_total_lz_bytes += match_len; @@ -2492,145 +3492,176 @@ static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match match_dist -= 1; d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); - d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3; + d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); + d->m_pLZ_code_buf += 3; - *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } + *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); + if (--d->m_num_flags_left == 0) { + d->m_num_flags_left = 8; + d->m_pLZ_flags = d->m_pLZ_code_buf++; + } - s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; - if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; + if (match_len >= TDEFL_MIN_MATCH_LEN) + d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; } -static mz_bool tdefl_compress_normal(tdefl_compressor *d) -{ - const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left; +static mz_bool tdefl_compress_normal(tdefl_compressor *d) { + const mz_uint8 *pSrc = d->m_pSrc; + size_t src_buf_left = d->m_src_buf_left; tdefl_flush flush = d->m_flush; - while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) - { + while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) { mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; - // Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. - if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) - { - mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; - mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; - mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); + // Update dictionary and hash chains. Keeps the lookahead size equal to + // TDEFL_MAX_MATCH_LEN. + if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) { + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & + TDEFL_LZ_DICT_SIZE_MASK, + ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; + mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] + << TDEFL_LZ_HASH_SHIFT) ^ + d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( + src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; src_buf_left -= num_bytes_to_process; d->m_lookahead_size += num_bytes_to_process; - while (pSrc != pSrc_end) - { - mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; - hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); - d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); - dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++; - } - } - else - { - while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) - { + while (pSrc != pSrc_end) { mz_uint8 c = *pSrc++; - mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)(ins_pos); + dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + ins_pos++; + } + } else { + while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) { + mz_uint8 c = *pSrc++; + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & + TDEFL_LZ_DICT_SIZE_MASK; src_buf_left--; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; - if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) - { + if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) { mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; - mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); - d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); + mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] + << (TDEFL_LZ_HASH_SHIFT * 2)) ^ + (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] + << TDEFL_LZ_HASH_SHIFT) ^ + c) & + (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)(ins_pos); } } } - d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); + d->m_dict_size = + MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) break; // Simple lazy/greedy parsing state machine. - len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; - if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) - { - if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) - { + len_to_move = 1; + cur_match_dist = 0; + cur_match_len = + d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); + cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) { + if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) { mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; - cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; } - if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1; + cur_match_len = 0; + while (cur_match_len < d->m_lookahead_size) { + if (d->m_dict[cur_pos + cur_match_len] != c) + break; + cur_match_len++; + } + if (cur_match_len < TDEFL_MIN_MATCH_LEN) + cur_match_len = 0; + else + cur_match_dist = 1; } + } else { + tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, + d->m_lookahead_size, &cur_match_dist, &cur_match_len); } - else - { - tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); - } - if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) - { + if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && + (cur_match_dist >= 8U * 1024U)) || + (cur_pos == cur_match_dist) || + ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) { cur_match_dist = cur_match_len = 0; } - if (d->m_saved_match_len) - { - if (cur_match_len > d->m_saved_match_len) - { + if (d->m_saved_match_len) { + if (cur_match_len > d->m_saved_match_len) { tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); - if (cur_match_len >= 128) - { + if (cur_match_len >= 128) { tdefl_record_match(d, cur_match_len, cur_match_dist); - d->m_saved_match_len = 0; len_to_move = cur_match_len; + d->m_saved_match_len = 0; + len_to_move = cur_match_len; + } else { + d->m_saved_lit = d->m_dict[cur_pos]; + d->m_saved_match_dist = cur_match_dist; + d->m_saved_match_len = cur_match_len; } - else - { - d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; - } - } - else - { + } else { tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); - len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0; + len_to_move = d->m_saved_match_len - 1; + d->m_saved_match_len = 0; } - } - else if (!cur_match_dist) - tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); - else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) - { + } else if (!cur_match_dist) + tdefl_record_literal(d, + d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); + else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || + (cur_match_len >= 128)) { tdefl_record_match(d, cur_match_len, cur_match_dist); len_to_move = cur_match_len; - } - else - { - d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; + } else { + d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; + d->m_saved_match_dist = cur_match_dist; + d->m_saved_match_len = cur_match_len; } // Move the lookahead forward by len_to_move bytes. d->m_lookahead_pos += len_to_move; MZ_ASSERT(d->m_lookahead_size >= len_to_move); d->m_lookahead_size -= len_to_move; d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, TDEFL_LZ_DICT_SIZE); - // Check if it's time to flush the current LZ codes to the internal output buffer. - if ( (d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || - ( (d->m_total_lz_bytes > 31*1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) ) - { + // Check if it's time to flush the current LZ codes to the internal output + // buffer. + if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || + ((d->m_total_lz_bytes > 31 * 1024) && + (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= + d->m_total_lz_bytes) || + (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) { int n; - d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; + d->m_pSrc = pSrc; + d->m_src_buf_left = src_buf_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; } } - d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; + d->m_pSrc = pSrc; + d->m_src_buf_left = src_buf_left; return MZ_TRUE; } -static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) -{ - if (d->m_pIn_buf_size) - { +static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) { + if (d->m_pIn_buf_size) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; } - if (d->m_pOut_buf_size) - { - size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); - memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); + if (d->m_pOut_buf_size) { + size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, + d->m_output_flush_remaining); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, + d->m_output_buf + d->m_output_flush_ofs, n); d->m_output_flush_ofs += (mz_uint)n; d->m_output_flush_remaining -= (mz_uint)n; d->m_out_buf_ofs += n; @@ -2638,29 +3669,40 @@ static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) *d->m_pOut_buf_size = d->m_out_buf_ofs; } - return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; + return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE + : TDEFL_STATUS_OKAY; } -tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) -{ - if (!d) - { - if (pIn_buf_size) *pIn_buf_size = 0; - if (pOut_buf_size) *pOut_buf_size = 0; +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, + size_t *pIn_buf_size, void *pOut_buf, + size_t *pOut_buf_size, tdefl_flush flush) { + if (!d) { + if (pIn_buf_size) + *pIn_buf_size = 0; + if (pOut_buf_size) + *pOut_buf_size = 0; return TDEFL_STATUS_BAD_PARAM; } - d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size; - d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size; - d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; + d->m_pIn_buf = pIn_buf; + d->m_pIn_buf_size = pIn_buf_size; + d->m_pOut_buf = pOut_buf; + d->m_pOut_buf_size = pOut_buf_size; + d->m_pSrc = (const mz_uint8 *)(pIn_buf); + d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; d->m_out_buf_ofs = 0; d->m_flush = flush; - if ( ((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || - (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf) ) - { - if (pIn_buf_size) *pIn_buf_size = 0; - if (pOut_buf_size) *pOut_buf_size = 0; + if (((d->m_pPut_buf_func != NULL) == + ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || + (d->m_prev_return_status != TDEFL_STATUS_OKAY) || + (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || + (pIn_buf_size && *pIn_buf_size && !pIn_buf) || + (pOut_buf_size && *pOut_buf_size && !pOut_buf)) { + if (pIn_buf_size) + *pIn_buf_size = 0; + if (pOut_buf_size) + *pOut_buf_size = 0; return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); } d->m_wants_to_finish |= (flush == TDEFL_FINISH); @@ -2671,179 +3713,329 @@ tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pI #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && - ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) - { + ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | + TDEFL_RLE_MATCHES)) == 0)) { if (!tdefl_compress_fast(d)) return d->m_prev_return_status; - } - else + } else #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN { if (!tdefl_compress_normal(d)) return d->m_prev_return_status; } - if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) - d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); + if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && + (pIn_buf)) + d->m_adler32 = + (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, + d->m_pSrc - (const mz_uint8 *)pIn_buf); - if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) - { + if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && + (!d->m_output_flush_remaining)) { if (tdefl_flush_block(d, flush) < 0) return d->m_prev_return_status; d->m_finished = (flush == TDEFL_FINISH); - if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; } + if (flush == TDEFL_FULL_FLUSH) { + MZ_CLEAR_OBJ(d->m_hash); + MZ_CLEAR_OBJ(d->m_next); + d->m_dict_size = 0; + } } return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); } -tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) -{ - MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, + size_t in_buf_size, tdefl_flush flush) { + MZ_ASSERT(d->m_pPut_buf_func); + return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); } -tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) -{ - d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user; - d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; +tdefl_status tdefl_init(tdefl_compressor *d, + tdefl_put_buf_func_ptr pPut_buf_func, + void *pPut_buf_user, int flags) { + d->m_pPut_buf_func = pPut_buf_func; + d->m_pPut_buf_user = pPut_buf_user; + d->m_flags = (mz_uint)(flags); + d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; + d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; - if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash); - d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; - d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; - d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; - d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY; - d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1; - d->m_pIn_buf = NULL; d->m_pOut_buf = NULL; - d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL; - d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0; - memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); - memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) + MZ_CLEAR_OBJ(d->m_hash); + d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = + d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; + d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = + d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; + d->m_pLZ_flags = d->m_lz_code_buf; + d->m_num_flags_left = 8; + d->m_pOutput_buf = d->m_output_buf; + d->m_pOutput_buf_end = d->m_output_buf; + d->m_prev_return_status = TDEFL_STATUS_OKAY; + d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; + d->m_adler32 = 1; + d->m_pIn_buf = NULL; + d->m_pOut_buf = NULL; + d->m_pIn_buf_size = NULL; + d->m_pOut_buf_size = NULL; + d->m_flush = TDEFL_NO_FLUSH; + d->m_pSrc = NULL; + d->m_src_buf_left = 0; + d->m_out_buf_ofs = 0; + memset(&d->m_huff_count[0][0], 0, + sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, + sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); return TDEFL_STATUS_OKAY; } -tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) -{ +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) { return d->m_prev_return_status; } -mz_uint32 tdefl_get_adler32(tdefl_compressor *d) -{ - return d->m_adler32; +mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; } + +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, + tdefl_put_buf_func_ptr pPut_buf_func, + void *pPut_buf_user, int flags) { + tdefl_compressor *pComp; + mz_bool succeeded; + if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) + return MZ_FALSE; + pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); + if (!pComp) + return MZ_FALSE; + succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == + TDEFL_STATUS_OKAY); + succeeded = + succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == + TDEFL_STATUS_DONE); + MZ_FREE(pComp); + return succeeded; } -mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) -{ - tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE; - pComp = (tdefl_compressor*)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE; - succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); - succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); - MZ_FREE(pComp); return succeeded; -} - -typedef struct -{ +typedef struct { size_t m_size, m_capacity; mz_uint8 *m_pBuf; mz_bool m_expandable; } tdefl_output_buffer; -static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) -{ +static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, + void *pUser) { tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; size_t new_size = p->m_size + len; - if (new_size > p->m_capacity) - { - size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE; - do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity); - pNew_buf = (mz_uint8*)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE; - p->m_pBuf = pNew_buf; p->m_capacity = new_capacity; + if (new_size > p->m_capacity) { + size_t new_capacity = p->m_capacity; + mz_uint8 *pNew_buf; + if (!p->m_expandable) + return MZ_FALSE; + do { + new_capacity = MZ_MAX(128U, new_capacity << 1U); + } while (new_size > new_capacity); + pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity); + if (!pNew_buf) + return MZ_FALSE; + p->m_pBuf = pNew_buf; + p->m_capacity = new_capacity; } - memcpy((mz_uint8*)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size; + memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len); + p->m_size = new_size; return MZ_TRUE; } -void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) -{ - tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); - if (!pOut_len) return MZ_FALSE; else *pOut_len = 0; +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, + size_t *pOut_len, int flags) { + tdefl_output_buffer out_buf; + MZ_CLEAR_OBJ(out_buf); + if (!pOut_len) + return MZ_FALSE; + else + *pOut_len = 0; out_buf.m_expandable = MZ_TRUE; - if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL; - *pOut_len = out_buf.m_size; return out_buf.m_pBuf; + if (!tdefl_compress_mem_to_output( + pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + return NULL; + *pOut_len = out_buf.m_size; + return out_buf.m_pBuf; } -size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) -{ - tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); - if (!pOut_buf) return 0; - out_buf.m_pBuf = (mz_uint8*)pOut_buf; out_buf.m_capacity = out_buf_len; - if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0; +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, + const void *pSrc_buf, size_t src_buf_len, + int flags) { + tdefl_output_buffer out_buf; + MZ_CLEAR_OBJ(out_buf); + if (!pOut_buf) + return 0; + out_buf.m_pBuf = (mz_uint8 *)pOut_buf; + out_buf.m_capacity = out_buf_len; + if (!tdefl_compress_mem_to_output( + pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + return 0; return out_buf.m_size; } #ifndef MINIZ_NO_ZLIB_APIS -static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; +static const mz_uint s_tdefl_num_probes[11] = {0, 1, 6, 32, 16, 32, + 128, 256, 512, 768, 1500}; -// level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). -mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) -{ - mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); - if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER; +// level may actually range from [0,10] (10 is a "hidden" max level, where we +// want a bit more compression and it's fine if throughput to fall off a cliff +// on some files). +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, + int strategy) { + mz_uint comp_flags = + s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | + ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); + if (window_bits > 0) + comp_flags |= TDEFL_WRITE_ZLIB_HEADER; - if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; - else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES; - else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK; - else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; - else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES; + if (!level) + comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; + else if (strategy == MZ_FILTERED) + comp_flags |= TDEFL_FILTER_MATCHES; + else if (strategy == MZ_HUFFMAN_ONLY) + comp_flags &= ~TDEFL_MAX_PROBES_MASK; + else if (strategy == MZ_FIXED) + comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; + else if (strategy == MZ_RLE) + comp_flags |= TDEFL_RLE_MATCHES; return comp_flags; } -#endif //MINIZ_NO_ZLIB_APIS +#endif // MINIZ_NO_ZLIB_APIS #ifdef _MSC_VER -#pragma warning (push) -#pragma warning (disable:4204) // nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) +#pragma warning(push) +#pragma warning(disable : 4204) // nonstandard extension used : non-constant + // aggregate initializer (also supported by GNU + // C and C99, so no big deal) #endif -// Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at +// Simple PNG writer function by Alex Evans, 2011. Released into the public +// domain: https://gist.github.com/908299, more context at // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. -// This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck. -void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip) -{ - // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined. - static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; - tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0; - if (!pComp) return NULL; - MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57+MZ_MAX(64, (1+bpl)*h); if (NULL == (out_buf.m_pBuf = (mz_uint8*)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; } +// This is actually a modification of Alex's original code so PNG files +// generated by this function pass pngcheck. +void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, + int h, int num_chans, + size_t *pLen_out, + mz_uint level, mz_bool flip) { + // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was + // defined. + static const mz_uint s_tdefl_png_num_probes[11] = { + 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500}; + tdefl_compressor *pComp = + (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); + tdefl_output_buffer out_buf; + int i, bpl = w * num_chans, y, z; + mz_uint32 c; + *pLen_out = 0; + if (!pComp) + return NULL; + MZ_CLEAR_OBJ(out_buf); + out_buf.m_expandable = MZ_TRUE; + out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); + if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) { + MZ_FREE(pComp); + return NULL; + } // write dummy header - for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf); + for (z = 41; z; --z) + tdefl_output_buffer_putter(&z, 1, &out_buf); // compress image data - tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); - for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8*)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); } - if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } + tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, + s_tdefl_png_num_probes[MZ_MIN(10, level)] | + TDEFL_WRITE_ZLIB_HEADER); + for (y = 0; y < h; ++y) { + tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); + tdefl_compress_buffer(pComp, + (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, + bpl, TDEFL_NO_FLUSH); + } + if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != + TDEFL_STATUS_DONE) { + MZ_FREE(pComp); + MZ_FREE(out_buf.m_pBuf); + return NULL; + } // write real header - *pLen_out = out_buf.m_size-41; + *pLen_out = out_buf.m_size - 41; { static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06}; - mz_uint8 pnghdr[41]={0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52, - 0,0,(mz_uint8)(w>>8),(mz_uint8)w,0,0,(mz_uint8)(h>>8),(mz_uint8)h,8,chans[num_chans],0,0,0,0,0,0,0, - (mz_uint8)(*pLen_out>>24),(mz_uint8)(*pLen_out>>16),(mz_uint8)(*pLen_out>>8),(mz_uint8)*pLen_out,0x49,0x44,0x41,0x54}; - c=(mz_uint32)mz_crc32(MZ_CRC32_INIT,pnghdr+12,17); for (i=0; i<4; ++i, c<<=8) ((mz_uint8*)(pnghdr+29))[i]=(mz_uint8)(c>>24); + mz_uint8 pnghdr[41] = {0x89, + 0x50, + 0x4e, + 0x47, + 0x0d, + 0x0a, + 0x1a, + 0x0a, + 0x00, + 0x00, + 0x00, + 0x0d, + 0x49, + 0x48, + 0x44, + 0x52, + 0, + 0, + (mz_uint8)(w >> 8), + (mz_uint8)w, + 0, + 0, + (mz_uint8)(h >> 8), + (mz_uint8)h, + 8, + chans[num_chans], + 0, + 0, + 0, + 0, + 0, + 0, + 0, + (mz_uint8)(*pLen_out >> 24), + (mz_uint8)(*pLen_out >> 16), + (mz_uint8)(*pLen_out >> 8), + (mz_uint8)*pLen_out, + 0x49, + 0x44, + 0x41, + 0x54}; + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); + for (i = 0; i < 4; ++i, c <<= 8) + ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); memcpy(out_buf.m_pBuf, pnghdr, 41); } // write footer (IDAT CRC-32, followed by IEND chunk) - if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } - c = (mz_uint32)mz_crc32(MZ_CRC32_INIT,out_buf.m_pBuf+41-4, *pLen_out+4); for (i=0; i<4; ++i, c<<=8) (out_buf.m_pBuf+out_buf.m_size-16)[i] = (mz_uint8)(c >> 24); + if (!tdefl_output_buffer_putter( + "\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { + *pLen_out = 0; + MZ_FREE(pComp); + MZ_FREE(out_buf.m_pBuf); + return NULL; + } + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, + *pLen_out + 4); + for (i = 0; i < 4; ++i, c <<= 8) + (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); // compute final size of file, grab compressed data buffer and return - *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf; + *pLen_out += 57; + MZ_FREE(pComp); + return out_buf.m_pBuf; } -void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) -{ - // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out) - return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, + int num_chans, size_t *pLen_out) { + // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we + // can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's + // where #defined out) + return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, + pLen_out, 6, MZ_FALSE); } #ifdef _MSC_VER -#pragma warning (pop) +#pragma warning(pop) #endif // ------------------- .ZIP archive reading @@ -2851,138 +4043,171 @@ void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, #ifndef MINIZ_NO_ARCHIVE_APIS #ifdef MINIZ_NO_STDIO - #define MZ_FILE void * +#define MZ_FILE void * #else - #include - #include +#include +#include - #if defined(_MSC_VER) || defined(__MINGW64__) - static FILE *mz_fopen(const char *pFilename, const char *pMode) - { - FILE* pFile = NULL; - fopen_s(&pFile, pFilename, pMode); - return pFile; - } - static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) - { - FILE* pFile = NULL; - if (freopen_s(&pFile, pPath, pMode, pStream)) - return NULL; - return pFile; - } - #ifndef MINIZ_NO_TIME - #include - #endif - #define MZ_FILE FILE - #define MZ_FOPEN mz_fopen - #define MZ_FCLOSE fclose - #define MZ_FREAD fread - #define MZ_FWRITE fwrite - #define MZ_FTELL64 _ftelli64 - #define MZ_FSEEK64 _fseeki64 - #define MZ_FILE_STAT_STRUCT _stat - #define MZ_FILE_STAT _stat - #define MZ_FFLUSH fflush - #define MZ_FREOPEN mz_freopen - #define MZ_DELETE_FILE remove - #elif defined(__MINGW32__) - #ifndef MINIZ_NO_TIME - #include - #endif - #define MZ_FILE FILE - #define MZ_FOPEN(f, m) fopen(f, m) - #define MZ_FCLOSE fclose - #define MZ_FREAD fread - #define MZ_FWRITE fwrite - #define MZ_FTELL64 ftello64 - #define MZ_FSEEK64 fseeko64 - #define MZ_FILE_STAT_STRUCT _stat - #define MZ_FILE_STAT _stat - #define MZ_FFLUSH fflush - #define MZ_FREOPEN(f, m, s) freopen(f, m, s) - #define MZ_DELETE_FILE remove - #elif defined(__TINYC__) - #ifndef MINIZ_NO_TIME - #include - #endif - #define MZ_FILE FILE - #define MZ_FOPEN(f, m) fopen(f, m) - #define MZ_FCLOSE fclose - #define MZ_FREAD fread - #define MZ_FWRITE fwrite - #define MZ_FTELL64 ftell - #define MZ_FSEEK64 fseek - #define MZ_FILE_STAT_STRUCT stat - #define MZ_FILE_STAT stat - #define MZ_FFLUSH fflush - #define MZ_FREOPEN(f, m, s) freopen(f, m, s) - #define MZ_DELETE_FILE remove - #elif defined(__GNUC__) && _LARGEFILE64_SOURCE - #ifndef MINIZ_NO_TIME - #include - #endif - #define MZ_FILE FILE - #define MZ_FOPEN(f, m) fopen64(f, m) - #define MZ_FCLOSE fclose - #define MZ_FREAD fread - #define MZ_FWRITE fwrite - #define MZ_FTELL64 ftello64 - #define MZ_FSEEK64 fseeko64 - #define MZ_FILE_STAT_STRUCT stat64 - #define MZ_FILE_STAT stat64 - #define MZ_FFLUSH fflush - #define MZ_FREOPEN(p, m, s) freopen64(p, m, s) - #define MZ_DELETE_FILE remove - #else - #ifndef MINIZ_NO_TIME - #include - #endif - #define MZ_FILE FILE - #define MZ_FOPEN(f, m) fopen(f, m) - #define MZ_FCLOSE fclose - #define MZ_FREAD fread - #define MZ_FWRITE fwrite - #define MZ_FTELL64 ftello - #define MZ_FSEEK64 fseeko - #define MZ_FILE_STAT_STRUCT stat - #define MZ_FILE_STAT stat - #define MZ_FFLUSH fflush - #define MZ_FREOPEN(f, m, s) freopen(f, m, s) - #define MZ_DELETE_FILE remove - #endif // #ifdef _MSC_VER +#if defined(_MSC_VER) +static FILE *mz_fopen(const char *pFilename, const char *pMode) { + FILE *pFile = NULL; + fopen_s(&pFile, pFilename, pMode); + return pFile; +} +static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) { + FILE *pFile = NULL; + if (freopen_s(&pFile, pPath, pMode, pStream)) + return NULL; + return pFile; +} +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FILE FILE +#define MZ_FOPEN mz_fopen +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 _ftelli64 +#define MZ_FSEEK64 _fseeki64 +#define MZ_FILE_STAT_STRUCT _stat +#define MZ_FILE_STAT _stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN mz_freopen +#define MZ_DELETE_FILE remove +#elif defined(__MINGW32__) +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FILE FILE +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftell +#define MZ_FSEEK64 fseek +#define MZ_FILE_STAT_STRUCT _stat +#define MZ_FILE_STAT _stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#elif defined(__TINYC__) +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FILE FILE +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftell +#define MZ_FSEEK64 fseek +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#elif defined(__GNUC__) && _LARGEFILE64_SOURCE +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FILE FILE +#define MZ_FOPEN(f, m) fopen64(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello64 +#define MZ_FSEEK64 fseeko64 +#define MZ_FILE_STAT_STRUCT stat64 +#define MZ_FILE_STAT stat64 +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(p, m, s) freopen64(p, m, s) +#define MZ_DELETE_FILE remove +#else +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FILE FILE +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#if _FILE_OFFSET_BITS == 64 || _POSIX_C_SOURCE >= 200112L +#define MZ_FTELL64 ftello +#define MZ_FSEEK64 fseeko +#else +#define MZ_FTELL64 ftell +#define MZ_FSEEK64 fseek +#endif +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#endif // #ifdef _MSC_VER #endif // #ifdef MINIZ_NO_STDIO #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) -// Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. -enum -{ +// Various ZIP archive enums. To completely avoid cross platform compiler +// alignment and platform endian issues, miniz.c doesn't use structs for any of +// this stuff. +enum { // ZIP archive identifiers and record sizes - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, - MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, + MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, // Central directory header record offsets - MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, - MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, - MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, - MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, + MZ_ZIP_CDH_SIG_OFS = 0, + MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, + MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, + MZ_ZIP_CDH_BIT_FLAG_OFS = 8, + MZ_ZIP_CDH_METHOD_OFS = 10, + MZ_ZIP_CDH_FILE_TIME_OFS = 12, + MZ_ZIP_CDH_FILE_DATE_OFS = 14, + MZ_ZIP_CDH_CRC32_OFS = 16, + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, + MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, + MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, + MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, + MZ_ZIP_CDH_DISK_START_OFS = 34, + MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, + MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, // Local directory header offsets - MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, - MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, - MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, + MZ_ZIP_LDH_SIG_OFS = 0, + MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, + MZ_ZIP_LDH_BIT_FLAG_OFS = 6, + MZ_ZIP_LDH_METHOD_OFS = 8, + MZ_ZIP_LDH_FILE_TIME_OFS = 10, + MZ_ZIP_LDH_FILE_DATE_OFS = 12, + MZ_ZIP_LDH_CRC32_OFS = 14, + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, + MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, + MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, // End of central directory offsets - MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, - MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, + MZ_ZIP_ECDH_SIG_OFS = 0, + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, + MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, + MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, + MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, }; -typedef struct -{ +typedef struct { void *m_p; size_t m_size, m_capacity; mz_uint m_element_size; } mz_zip_array; -struct mz_zip_internal_state_tag -{ +struct mz_zip_internal_state_tag { mz_zip_array m_central_dir; mz_zip_array m_central_dir_offsets; mz_zip_array m_sorted_central_dir_offsets; @@ -2992,232 +4217,324 @@ struct mz_zip_internal_state_tag size_t m_mem_capacity; }; -#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size -#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index] +#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) \ + (array_ptr)->m_element_size = element_size +#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \ + ((element_type *)((array_ptr)->m_p))[index] -static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) -{ +static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, + mz_zip_array *pArray) { pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); memset(pArray, 0, sizeof(mz_zip_array)); } -static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) -{ - void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE; - if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; } - if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE; - pArray->m_p = pNew_p; pArray->m_capacity = new_capacity; +static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, + mz_zip_array *pArray, + size_t min_new_capacity, + mz_uint growing) { + void *pNew_p; + size_t new_capacity = min_new_capacity; + MZ_ASSERT(pArray->m_element_size); + if (pArray->m_capacity >= min_new_capacity) + return MZ_TRUE; + if (growing) { + new_capacity = MZ_MAX(1, pArray->m_capacity); + while (new_capacity < min_new_capacity) + new_capacity *= 2; + } + if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, + pArray->m_element_size, new_capacity))) + return MZ_FALSE; + pArray->m_p = pNew_p; + pArray->m_capacity = new_capacity; return MZ_TRUE; } -static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) -{ - if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; } +static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, + mz_zip_array *pArray, + size_t new_capacity, + mz_uint growing) { + if (new_capacity > pArray->m_capacity) { + if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) + return MZ_FALSE; + } return MZ_TRUE; } -static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) -{ - if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; } +static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, + mz_zip_array *pArray, + size_t new_size, + mz_uint growing) { + if (new_size > pArray->m_capacity) { + if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) + return MZ_FALSE; + } pArray->m_size = new_size; return MZ_TRUE; } -static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) -{ +static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, + mz_zip_array *pArray, + size_t n) { return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); } -static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) -{ - if (n==0) return MZ_TRUE; - assert(NULL!=pElements); - size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE; - memcpy((mz_uint8*)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); +static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, + mz_zip_array *pArray, + const void *pElements, + size_t n) { + if (0 == n) + return MZ_TRUE; + if (!pElements) + return MZ_FALSE; + + size_t orig_size = pArray->m_size; + if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) + return MZ_FALSE; + memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, + pElements, n * pArray->m_element_size); return MZ_TRUE; } #ifndef MINIZ_NO_TIME -static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) -{ +static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) { struct tm tm; - memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; - tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31; - tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62; + memset(&tm, 0, sizeof(tm)); + tm.tm_isdst = -1; + tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; + tm.tm_mon = ((dos_date >> 5) & 15) - 1; + tm.tm_mday = dos_date & 31; + tm.tm_hour = (dos_time >> 11) & 31; + tm.tm_min = (dos_time >> 5) & 63; + tm.tm_sec = (dos_time << 1) & 62; return mktime(&tm); } -static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) -{ +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS +static void mz_zip_time_t_to_dos_time(time_t time, mz_uint16 *pDOS_time, + mz_uint16 *pDOS_date) { #ifdef _MSC_VER struct tm tm_struct; struct tm *tm = &tm_struct; errno_t err = localtime_s(tm, &time); - if (err) - { - *pDOS_date = 0; *pDOS_time = 0; + if (err) { + *pDOS_date = 0; + *pDOS_time = 0; return; } #else struct tm *tm = localtime(&time); -#endif - *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); - *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); +#endif /* #ifdef _MSC_VER */ + + *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + + ((tm->tm_sec) >> 1)); + *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + + ((tm->tm_mon + 1) << 5) + tm->tm_mday); } -#endif +#endif /* MINIZ_NO_ARCHIVE_WRITING_APIS */ #ifndef MINIZ_NO_STDIO -static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) -{ -#ifdef MINIZ_NO_TIME - (void)pFilename; *pDOS_date = *pDOS_time = 0; -#else +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS +static mz_bool mz_zip_get_file_modified_time(const char *pFilename, + time_t *pTime) { struct MZ_FILE_STAT_STRUCT file_stat; - // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. + + /* On Linux with x86 glibc, this call will fail on large files (I think >= + * 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. */ if (MZ_FILE_STAT(pFilename, &file_stat) != 0) return MZ_FALSE; - mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date); -#endif // #ifdef MINIZ_NO_TIME + + *pTime = file_stat.st_mtime; + return MZ_TRUE; } +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS*/ + +static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, + time_t modified_time) { + struct utimbuf t; + + memset(&t, 0, sizeof(t)); + t.actime = access_time; + t.modtime = modified_time; -#ifndef MINIZ_NO_TIME -static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time) -{ - struct utimbuf t; t.actime = access_time; t.modtime = modified_time; return !utime(pFilename, &t); } -#endif // #ifndef MINIZ_NO_TIME -#endif // #ifndef MINIZ_NO_STDIO +#endif /* #ifndef MINIZ_NO_STDIO */ +#endif /* #ifndef MINIZ_NO_TIME */ -static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags) -{ +static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, + mz_uint32 flags) { (void)flags; if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; - if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; - if (!pZip->m_pFree) pZip->m_pFree = def_free_func; - if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; + if (!pZip->m_pAlloc) + pZip->m_pAlloc = def_alloc_func; + if (!pZip->m_pFree) + pZip->m_pFree = def_free_func; + if (!pZip->m_pRealloc) + pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_READING; pZip->m_archive_size = 0; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; - if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc( + pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, + sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, + sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, + sizeof(mz_uint32)); return MZ_TRUE; } -static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) -{ - const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; - const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); - mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); +static MZ_FORCEINLINE mz_bool +mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, + const mz_zip_array *pCentral_dir_offsets, + mz_uint l_index, mz_uint r_index) { + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT( + pCentral_dir_array, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, + l_index)), + *pE; + const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT( + pCentral_dir_array, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), + r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; - pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); - while (pL < pE) - { + while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; - pL++; pR++; + pL++; + pR++; } return (pL == pE) ? (l_len < r_len) : (l < r); } -#define MZ_SWAP_UINT32(a, b) do { mz_uint32 t = a; a = b; b = t; } MZ_MACRO_END +#define MZ_SWAP_UINT32(a, b) \ + do { \ + mz_uint32 t = a; \ + a = b; \ + b = t; \ + } \ + MZ_MACRO_END -// Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) -static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) -{ +// Heap sort of lowercased filenames, used to help accelerate plain central +// directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), +// but it could allocate memory.) +static void +mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; - mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT( + &pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; int start = (size - 2) >> 1, end; - while (start >= 0) - { + while (start >= 0) { int child, root = start; - for ( ; ; ) - { + for (;;) { if ((child = (root << 1) + 1) >= size) break; - child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]))); - if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + child += + (((child + 1) < size) && + (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, + pIndices[child], pIndices[child + 1]))); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, + pIndices[root], pIndices[child])) break; - MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); + root = child; } start--; } end = size - 1; - while (end > 0) - { + while (end > 0) { int child, root = 0; MZ_SWAP_UINT32(pIndices[end], pIndices[0]); - for ( ; ; ) - { + for (;;) { if ((child = (root << 1) + 1) >= end) break; - child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])); - if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + child += + (((child + 1) < end) && + mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, + pIndices[child], pIndices[child + 1])); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, + pIndices[root], pIndices[child])) break; - MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); + root = child; } end--; } } -static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags) -{ +static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, + mz_uint32 flags) { mz_uint cdir_size, num_this_disk, cdir_disk_index; mz_uint64 cdir_ofs; mz_int64 cur_file_ofs; const mz_uint8 *p; - mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; - mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); - // Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. + mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; + mz_uint8 *pBuf = (mz_uint8 *)buf_u32; + mz_bool sort_central_dir = + ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); + // Basic sanity checks - reject files which are too small, and check the first + // 4 bytes of the file to make sure a local header is there. if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; - // Find the end of central directory record by scanning the file from the end towards the beginning. - cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); - for ( ; ; ) - { - int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); + // Find the end of central directory record by scanning the file from the end + // towards the beginning. + cur_file_ofs = + MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); + for (;;) { + int i, + n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) return MZ_FALSE; for (i = n - 4; i >= 0; --i) if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) break; - if (i >= 0) - { + if (i >= 0) { cur_file_ofs += i; break; } - if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) + if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= + (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) return MZ_FALSE; cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); } // Read and verify the end of central directory record. - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; - if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) || - ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS))) + if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) || + ((pZip->m_total_files = + MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != + MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS))) return MZ_FALSE; num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); - if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) + if (((num_this_disk | cdir_disk_index) != 0) && + ((num_this_disk != 1) || (cdir_disk_index != 1))) return MZ_FALSE; - if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) + if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < + pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); @@ -3226,46 +4543,66 @@ static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 fl pZip->m_central_directory_file_ofs = cdir_ofs; - if (pZip->m_total_files) - { - mz_uint i, n; + if (pZip->m_total_files) { + mz_uint i, n; - // Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and another to hold the sorted indices. - if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || - (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) + // Read the entire central directory into a heap block, and allocate another + // heap block to hold the unsorted central dir file record offsets, and + // another to hold the sorted indices. + if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, + MZ_FALSE)) || + (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, + pZip->m_total_files, MZ_FALSE))) return MZ_FALSE; - if (sort_central_dir) - { - if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) + if (sort_central_dir) { + if (!mz_zip_array_resize(pZip, + &pZip->m_pState->m_sorted_central_dir_offsets, + pZip->m_total_files, MZ_FALSE)) return MZ_FALSE; } - if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) + if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, + pZip->m_pState->m_central_dir.m_p, + cdir_size) != cdir_size) return MZ_FALSE; - // Now create an index into the central directory file records, do some basic sanity checking on each record, and check for zip64 entries (which are not yet supported). + // Now create an index into the central directory file records, do some + // basic sanity checking on each record, and check for zip64 entries (which + // are not yet supported). p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; - for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) - { + for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) { mz_uint total_header_size, comp_size, decomp_size, disk_index; - if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) + if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || + (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) return MZ_FALSE; - MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, + i) = + (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); if (sort_central_dir) - MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, + mz_uint32, i) = i; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); - if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF)) + if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && + (decomp_size != comp_size)) || + (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || + (comp_size == 0xFFFFFFFF)) return MZ_FALSE; disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); if ((disk_index != num_this_disk) && (disk_index != 1)) return MZ_FALSE; - if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) + if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) return MZ_FALSE; - if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) + if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > + n) return MZ_FALSE; - n -= total_header_size; p += total_header_size; + n -= total_header_size; + p += total_header_size; } } @@ -3275,31 +4612,32 @@ static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 fl return MZ_TRUE; } -mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags) -{ +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, + mz_uint32 flags) { if ((!pZip) || (!pZip->m_pRead)) return MZ_FALSE; if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; - if (!mz_zip_reader_read_central_dir(pZip, flags)) - { + if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } -static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) -{ +static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, + void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; - size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); + size_t s = (file_ofs >= pZip->m_archive_size) + ? 0 + : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); return s; } -mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags) -{ +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, + size_t size, mz_uint32 flags) { if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; @@ -3311,8 +4649,7 @@ mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t si pZip->m_pState->m_pMem = (void *)pMem; #endif pZip->m_pState->m_mem_size = size; - if (!mz_zip_reader_read_central_dir(pZip, flags)) - { + if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } @@ -3320,29 +4657,29 @@ mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t si } #ifndef MINIZ_NO_STDIO -static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) -{ +static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, + void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); - if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + if (((mz_int64)file_ofs < 0) || + (((cur_ofs != (mz_int64)file_ofs)) && + (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); } -mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) -{ +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, + mz_uint32 flags) { mz_uint64 file_size; MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb"); if (!pFile) return MZ_FALSE; - if (MZ_FSEEK64(pFile, 0, SEEK_END)) - { + if (MZ_FSEEK64(pFile, 0, SEEK_END)) { MZ_FCLOSE(pFile); return MZ_FALSE; } file_size = MZ_FTELL64(pFile); - if (!mz_zip_reader_init_internal(pZip, flags)) - { + if (!mz_zip_reader_init_internal(pZip, flags)) { MZ_FCLOSE(pFile); return MZ_FALSE; } @@ -3350,8 +4687,7 @@ mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_ pZip->m_pIO_opaque = pZip; pZip->m_pState->m_pFile = pFile; pZip->m_archive_size = file_size; - if (!mz_zip_reader_read_central_dir(pZip, flags)) - { + if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } @@ -3359,20 +4695,23 @@ mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_ } #endif // #ifndef MINIZ_NO_STDIO -mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) -{ +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) { return pZip ? pZip->m_total_files : 0; } -static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh(mz_zip_archive *pZip, mz_uint file_index) -{ - if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) +static MZ_FORCEINLINE const mz_uint8 * +mz_zip_reader_get_cdh(mz_zip_archive *pZip, mz_uint file_index) { + if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || + (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return NULL; - return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); + return &MZ_ZIP_ARRAY_ELEMENT( + &pZip->m_pState->m_central_dir, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, + file_index)); } -mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) -{ +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, + mz_uint file_index) { mz_uint m_bit_flag; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) @@ -3381,8 +4720,8 @@ mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index return (m_bit_flag & 1); } -mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) -{ +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, + mz_uint file_index) { mz_uint filename_len, external_attr; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) @@ -3390,14 +4729,15 @@ mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_ind // First see if the filename ends with a '/' character. filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); - if (filename_len) - { + if (filename_len) { if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') return MZ_TRUE; } - // Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct. - // Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field. + // Bugfix: This code was also checking if the internal attribute was non-zero, + // which wasn't correct. Most/all zip writers (hopefully) set DOS + // file/directory attributes in the low 16-bits, so check for the DOS + // directory flag and ignore the source OS ID in the created by field. // FIXME: Remove this check? Is it necessary - we already check the filename. external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); if ((external_attr & 0x10) != 0) @@ -3406,8 +4746,8 @@ mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_ind return MZ_FALSE; } -mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) -{ +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, + mz_zip_archive_file_stat *pStat) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if ((!p) || (!pStat)) @@ -3415,13 +4755,16 @@ mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip // Unpack the central directory record. pStat->m_file_index = file_index; - pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); + pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT( + &pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); #ifndef MINIZ_NO_TIME - pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); + pStat->m_time = + mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), + MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); #endif pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); @@ -3431,24 +4774,35 @@ mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); // Copy as much of the filename and comment as possible. - n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); - memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0'; + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); + memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pStat->m_filename[n] = '\0'; - n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); + n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); + n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); pStat->m_comment_size = n; - memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0'; + memcpy(pStat->m_comment, + p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), + n); + pStat->m_comment[n] = '\0'; return MZ_TRUE; } -mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) -{ +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, + char *pFilename, mz_uint filename_buf_size) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); - if (!p) { if (filename_buf_size) pFilename[0] = '\0'; return 0; } + if (!p) { + if (filename_buf_size) + pFilename[0] = '\0'; + return 0; + } n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); - if (filename_buf_size) - { + if (filename_buf_size) { n = MZ_MIN(n, filename_buf_size - 1); memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pFilename[n] = '\0'; @@ -3456,8 +4810,10 @@ mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, cha return n + 1; } -static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) -{ +static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, + const char *pB, + mz_uint len, + mz_uint flags) { mz_uint i; if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) return 0 == memcmp(pA, pB, len); @@ -3467,34 +4823,43 @@ static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const c return MZ_TRUE; } -static MZ_FORCEINLINE int mz_zip_reader_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) -{ - const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; +static MZ_FORCEINLINE int +mz_zip_reader_filename_compare(const mz_zip_array *pCentral_dir_array, + const mz_zip_array *pCentral_dir_offsets, + mz_uint l_index, const char *pR, mz_uint r_len) { + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT( + pCentral_dir_array, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, + l_index)), + *pE; mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); - while (pL < pE) - { + while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; - pL++; pR++; + pL++; + pR++; } return (pL == pE) ? (int)(l_len - r_len) : (l - r); } -static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename) -{ +static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, + const char *pFilename) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; - mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT( + &pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; const mz_uint filename_len = (mz_uint)strlen(pFilename); int l = 0, h = size - 1; - while (l <= h) - { - int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); + while (l <= h) { + int m = (l + h) >> 1, file_index = pIndices[m], + comp = + mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, + file_index, pFilename, filename_len); if (!comp) return file_index; else if (comp < 0) @@ -3505,53 +4870,74 @@ static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const c return -1; } -int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) -{ - mz_uint file_index; size_t name_len, comment_len; - if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, + const char *pComment, mz_uint flags) { + mz_uint file_index; + size_t name_len, comment_len; + if ((!pZip) || (!pZip->m_pState) || (!pName) || + (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return -1; - if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) + if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && + (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) return mz_zip_reader_locate_file_binary_search(pZip, pName); - name_len = strlen(pName); if (name_len > 0xFFFF) return -1; - comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) return -1; - for (file_index = 0; file_index < pZip->m_total_files; file_index++) - { - const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); + name_len = strlen(pName); + if (name_len > 0xFFFF) + return -1; + comment_len = pComment ? strlen(pComment) : 0; + if (comment_len > 0xFFFF) + return -1; + for (file_index = 0; file_index < pZip->m_total_files; file_index++) { + const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT( + &pZip->m_pState->m_central_dir, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, + file_index)); mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); - const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + const char *pFilename = + (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; if (filename_len < name_len) continue; - if (comment_len) - { - mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); + if (comment_len) { + mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), + file_comment_len = + MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); const char *pFile_comment = pFilename + filename_len + file_extra_len; - if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags))) + if ((file_comment_len != comment_len) || + (!mz_zip_reader_string_equal(pComment, pFile_comment, + file_comment_len, flags))) continue; } - if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) - { + if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) { int ofs = filename_len - 1; - do - { - if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) + do { + if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || + (pFilename[ofs] == ':')) break; } while (--ofs >= 0); ofs++; - pFilename += ofs; filename_len -= ofs; + pFilename += ofs; + filename_len -= ofs; } - if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags))) + if ((filename_len == name_len) && + (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags))) return file_index; } return -1; } -mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) -{ +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, + mz_uint file_index, void *pBuf, + size_t buf_size, mz_uint flags, + void *pUser_read_buf, + size_t user_read_buf_size) { int status = TINFL_STATUS_DONE; - mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; + mz_uint64 needed_size, cur_file_ofs, comp_remaining, + out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; mz_zip_archive_file_stat file_stat; void *pRead_buf; - mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + mz_uint32 + local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / + sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; tinfl_decompressor inflator; if ((buf_size) && (!pBuf)) @@ -3560,12 +4946,15 @@ mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; - // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes) + // Empty file, or a directory (but not always a directory - I've seen odd zips + // with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; - // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers). - // I'm torn how to handle this case - should it fail instead? + // Entry is a subdirectory (I've seen old zips with dir entries which have + // compressed deflate data which inflates to 0 bytes, but these entries claim + // to uncompress to 512 bytes in the headers). I'm torn how to handle this + // case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; @@ -3574,45 +4963,51 @@ mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file return MZ_FALSE; // This function only supports stored and deflate. - if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && + (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Ensure supplied output buffer is large enough. - needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; + needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size + : file_stat.m_uncomp_size; if (buf_size < needed_size) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; - cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; - if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) - { + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, + (size_t)needed_size) != needed_size) return MZ_FALSE; - return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32); + return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || + (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, + (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32); } - // Decompress the file either directly from memory or from a file input buffer. + // Decompress the file either directly from memory or from a file input + // buffer. tinfl_init(&inflator); - if (pZip->m_pState->m_pMem) - { + if (pZip->m_pState->m_pMem) { // Read directly from the archive in memory. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; - } - else if (pUser_read_buf) - { + } else if (pUser_read_buf) { // Use a user provided read buffer. if (!user_read_buf_size) return MZ_FALSE; @@ -3620,31 +5015,30 @@ mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file read_buf_size = user_read_buf_size; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; - } - else - { + } else { // Temporarily allocate a read buffer. read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); #ifdef _MSC_VER - if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) + if (((0, sizeof(size_t) == sizeof(mz_uint32))) && + (read_buf_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #endif return MZ_FALSE; - if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, + (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } - do - { - size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); - if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) - { + do { + size_t in_buf_size, + out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) - { + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, + (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } @@ -3653,16 +5047,21 @@ mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; - status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); + status = tinfl_decompress( + &inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, + (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | + (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; out_buf_ofs += out_buf_size; } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); - if (status == TINFL_STATUS_DONE) - { + if (status == TINFL_STATUS_DONE) { // Make sure the entire file was decompressed, and check its CRC. - if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)) + if ((out_buf_ofs != file_stat.m_uncomp_size) || + (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, + (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } @@ -3672,26 +5071,33 @@ mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file return status == TINFL_STATUS_DONE; } -mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) -{ +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( + mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, + mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; - return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, + flags, pUser_read_buf, + user_read_buf_size); } -mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) -{ - return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, + void *pBuf, size_t buf_size, + mz_uint flags) { + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, + flags, NULL, 0); } -mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) -{ - return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, + const char *pFilename, void *pBuf, + size_t buf_size, mz_uint flags) { + return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, + buf_size, flags, NULL, 0); } -void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) -{ +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, + size_t *pSize, mz_uint flags) { mz_uint64 comp_size, uncomp_size, alloc_size; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); void *pBuf; @@ -3711,47 +5117,61 @@ void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, si if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #endif return NULL; - if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) + if (NULL == + (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) return NULL; - if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) - { + if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, + flags)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return NULL; } - if (pSize) *pSize = (size_t)alloc_size; + if (pSize) + *pSize = (size_t)alloc_size; return pBuf; } -void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) -{ +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, + const char *pFilename, size_t *pSize, + mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); - if (file_index < 0) - { - if (pSize) *pSize = 0; + if (file_index < 0) { + if (pSize) + *pSize = 0; return MZ_FALSE; } return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); } -mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) -{ - int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT; - mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, + mz_uint file_index, + mz_file_write_func pCallback, + void *pOpaque, mz_uint flags) { + int status = TINFL_STATUS_DONE; + mz_uint file_crc32 = MZ_CRC32_INIT; + mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, + out_buf_ofs = 0, cur_file_ofs; mz_zip_archive_file_stat file_stat; - void *pRead_buf = NULL; void *pWrite_buf = NULL; - mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + void *pRead_buf = NULL; + void *pWrite_buf = NULL; + mz_uint32 + local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / + sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; - // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes) + // Empty file, or a directory (but not always a directory - I've seen odd zips + // with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; - // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers). - // I'm torn how to handle this case - should it fail instead? + // Entry is a subdirectory (I've seen old zips with dir entries which have + // compressed deflate data which inflates to 0 bytes, but these entries claim + // to uncompress to 512 bytes in the headers). I'm torn how to handle this + // case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; @@ -3760,69 +5180,76 @@ mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_ind return MZ_FALSE; // This function only supports stored and deflate. - if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && + (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; - cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; - // Decompress the file either directly from memory or from a file input buffer. - if (pZip->m_pState->m_pMem) - { + // Decompress the file either directly from memory or from a file input + // buffer. + if (pZip->m_pState->m_pMem) { pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; - } - else - { + } else { read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); - if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, + (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } - if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) - { + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. - if (pZip->m_pState->m_pMem) - { + if (pZip->m_pState->m_pMem) { #ifdef _MSC_VER - if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) + if (((0, sizeof(size_t) == sizeof(mz_uint32))) && + (file_stat.m_comp_size > 0xFFFFFFFF)) #else - if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) + if (((sizeof(size_t) == sizeof(mz_uint32))) && + (file_stat.m_comp_size > 0xFFFFFFFF)) #endif return MZ_FALSE; - if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, + (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) status = TINFL_STATUS_FAILED; else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) - file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); + file_crc32 = + (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, + (size_t)file_stat.m_comp_size); + // cur_file_ofs += file_stat.m_comp_size; out_buf_ofs += file_stat.m_comp_size; - } - else - { - while (comp_remaining) - { + // comp_remaining = 0; + } else { + while (comp_remaining) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) - { + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, + (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) - file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); + file_crc32 = (mz_uint32)mz_crc32( + file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); - if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) - { + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, + (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } @@ -3831,25 +5258,24 @@ mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_ind comp_remaining -= read_buf_avail; } } - } - else - { + } else { tinfl_decompressor inflator; tinfl_init(&inflator); - if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) + if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, + TINFL_LZ_DICT_SIZE))) status = TINFL_STATUS_FAILED; - else - { - do - { - mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); - size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); - if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) - { + else { + do { + mz_uint8 *pWrite_buf_cur = + (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + size_t in_buf_size, + out_buf_size = + TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) - { + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, + (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } @@ -3859,32 +5285,36 @@ mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_ind } in_buf_size = (size_t)read_buf_avail; - status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); + status = tinfl_decompress( + &inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, + (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, + comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; - if (out_buf_size) - { - if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) - { + if (out_buf_size) { + if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != + out_buf_size) { status = TINFL_STATUS_FAILED; break; } - file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); - if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) - { + file_crc32 = + (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); + if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) { status = TINFL_STATUS_FAILED; break; } } - } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); + } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || + (status == TINFL_STATUS_HAS_MORE_OUTPUT)); } } - if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) - { + if ((status == TINFL_STATUS_DONE) && + (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) { // Make sure the entire file was decompressed, and check its CRC. - if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32)) + if ((out_buf_ofs != file_stat.m_uncomp_size) || + (file_crc32 != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } @@ -3896,72 +5326,82 @@ mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_ind return status == TINFL_STATUS_DONE; } -mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) -{ +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, + const char *pFilename, + mz_file_write_func pCallback, + void *pOpaque, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; - return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); + return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, + flags); } #ifndef MINIZ_NO_STDIO -static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) -{ - (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE*)pOpaque); +static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, + const void *pBuf, size_t n) { + (void)ofs; + return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque); } -mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) -{ +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, + const char *pDst_filename, + mz_uint flags) { mz_bool status; mz_zip_archive_file_stat file_stat; MZ_FILE *pFile; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; + pFile = MZ_FOPEN(pDst_filename, "wb"); if (!pFile) return MZ_FALSE; - status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); + status = mz_zip_reader_extract_to_callback( + pZip, file_index, mz_zip_file_write_callback, pFile, flags); if (MZ_FCLOSE(pFile) == EOF) return MZ_FALSE; #ifndef MINIZ_NO_TIME - if (status) + if (status) { mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); + } #endif + return status; } #endif // #ifndef MINIZ_NO_STDIO -mz_bool mz_zip_reader_end(mz_zip_archive *pZip) -{ - if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) +mz_bool mz_zip_reader_end(mz_zip_archive *pZip) { + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || + (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; - if (pZip->m_pState) - { - mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL; - mz_zip_array_clear(pZip, &pState->m_central_dir); - mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); - mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + mz_zip_internal_state *pState = pZip->m_pState; + pZip->m_pState = NULL; + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO - if (pState->m_pFile) - { - MZ_FCLOSE(pState->m_pFile); - pState->m_pFile = NULL; - } + if (pState->m_pFile) { + MZ_FCLOSE(pState->m_pFile); + pState->m_pFile = NULL; + } #endif // #ifndef MINIZ_NO_STDIO - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - } + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO -mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) -{ - int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags); +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, + const char *pArchive_filename, + const char *pDst_filename, + mz_uint flags) { + int file_index = + mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); @@ -3972,75 +5412,92 @@ mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pAr #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS -static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); } -static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); } +static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { + p[0] = (mz_uint8)v; + p[1] = (mz_uint8)(v >> 8); +} +static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { + p[0] = (mz_uint8)v; + p[1] = (mz_uint8)(v >> 8); + p[2] = (mz_uint8)(v >> 16); + p[3] = (mz_uint8)(v >> 24); +} #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) -mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) -{ - if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) { + if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || + (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; - if (pZip->m_file_offset_alignment) - { + if (pZip->m_file_offset_alignment) { // Ensure user specified file offset alignment is a power of 2. if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) return MZ_FALSE; } - if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; - if (!pZip->m_pFree) pZip->m_pFree = def_free_func; - if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; + if (!pZip->m_pAlloc) + pZip->m_pAlloc = def_alloc_func; + if (!pZip->m_pFree) + pZip->m_pFree = def_free_func; + if (!pZip->m_pRealloc) + pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_archive_size = existing_size; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; - if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc( + pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, + sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, + sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, + sizeof(mz_uint32)); return MZ_TRUE; } -static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) -{ +static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, + const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_zip_internal_state *pState = pZip->m_pState; mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); -#ifdef _MSC_VER - if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) -#else - if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) -#endif + + if ((!n) || + ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) return 0; - if (new_size > pState->m_mem_capacity) - { + + if (new_size > pState->m_mem_capacity) { void *pNew_block; - size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2; - if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) + size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); + while (new_capacity < new_size) + new_capacity *= 2; + if (NULL == (pNew_block = pZip->m_pRealloc( + pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) return 0; - pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity; + pState->m_pMem = pNew_block; + pState->m_mem_capacity = new_capacity; } memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); pState->m_mem_size = (size_t)new_size; return n; } -mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) -{ +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, + size_t size_to_reserve_at_beginning, + size_t initial_allocation_size) { pZip->m_pWrite = mz_zip_heap_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; - if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) - { - if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size))) - { + if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, + size_to_reserve_at_beginning))) { + if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc( + pZip->m_pAlloc_opaque, 1, initial_allocation_size))) { mz_zip_writer_end(pZip); return MZ_FALSE; } @@ -4050,61 +5507,65 @@ mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_ } #ifndef MINIZ_NO_STDIO -static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) -{ +static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, + const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); - if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + if (((mz_int64)file_ofs < 0) || + (((cur_ofs != (mz_int64)file_ofs)) && + (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); } -mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) -{ +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, + mz_uint64 size_to_reserve_at_beginning) { MZ_FILE *pFile; pZip->m_pWrite = mz_zip_file_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; - if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) - { + if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_pFile = pFile; - if (size_to_reserve_at_beginning) - { - mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf); - do - { + if (size_to_reserve_at_beginning) { + mz_uint64 cur_ofs = 0; + char buf[4096]; + MZ_CLEAR_OBJ(buf); + do { size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) - { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) { mz_zip_writer_end(pZip); return MZ_FALSE; } - cur_ofs += n; size_to_reserve_at_beginning -= n; + cur_ofs += n; + size_to_reserve_at_beginning -= n; } while (size_to_reserve_at_beginning); } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO -mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) -{ +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, + const char *pFilename) { mz_zip_internal_state *pState; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; - // No sense in trying to write to an archive that's already at the support max size - if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) + // No sense in trying to write to an archive that's already at the support max + // size + if ((pZip->m_total_files == 0xFFFF) || + ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; pState = pZip->m_pState; - if (pState->m_pFile) - { + if (pState->m_pFile) { #ifdef MINIZ_NO_STDIO - pFilename; return MZ_FALSE; + pFilename; + return MZ_FALSE; #else // Archive is being read from stdio - try to reopen as writable. if (pZip->m_pIO_opaque != pZip) @@ -4112,27 +5573,29 @@ mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilena if (!pFilename) return MZ_FALSE; pZip->m_pWrite = mz_zip_file_write_func; - if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) - { - // The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. + if (NULL == + (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) { + // The mz_zip_archive is now in a bogus state because pState->m_pFile is + // NULL, so just close it. mz_zip_reader_end(pZip); return MZ_FALSE; } #endif // #ifdef MINIZ_NO_STDIO - } - else if (pState->m_pMem) - { - // Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. + } else if (pState->m_pMem) { + // Archive lives in a memory block. Assume it's from the heap that we can + // resize using the realloc callback. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE; pState->m_mem_capacity = pState->m_mem_size; pZip->m_pWrite = mz_zip_heap_write_func; } - // Archive is being read via a user provided read function - make sure the user has specified a write function too. + // Archive is being read via a user provided read function - make sure the + // user has specified a write function too. else if (!pZip->m_pWrite) return MZ_FALSE; - // Start writing new files at the archive's current central directory location. + // Start writing new files at the archive's current central directory + // location. pZip->m_archive_size = pZip->m_central_directory_file_ofs; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_central_directory_file_ofs = 0; @@ -4140,30 +5603,36 @@ mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilena return MZ_TRUE; } -mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) -{ - return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, + const void *pBuf, size_t buf_size, + mz_uint level_and_flags) { + return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, + level_and_flags, 0, 0); } -typedef struct -{ +typedef struct { mz_zip_archive *m_pZip; mz_uint64 m_cur_archive_file_ofs; mz_uint64 m_comp_size; } mz_zip_writer_add_state; -static mz_bool mz_zip_writer_add_put_buf_callback(const void* pBuf, int len, void *pUser) -{ +static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, + void *pUser) { mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; - if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) + if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, + pState->m_cur_archive_file_ofs, pBuf, + len) != len) return MZ_FALSE; pState->m_cur_archive_file_ofs += len; pState->m_comp_size += len; return MZ_TRUE; } -static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) -{ +static mz_bool mz_zip_writer_create_local_dir_header( + mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, + mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, + mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, + mz_uint16 dos_time, mz_uint16 dos_date) { (void)pZip; memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); @@ -4180,11 +5649,19 @@ static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_ui return MZ_TRUE; } -static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) -{ +static mz_bool mz_zip_writer_create_central_dir_header( + mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, + mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, + mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, + mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, + mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { (void)pZip; + mz_uint16 version_made_by = 10 * MZ_VER_MAJOR + MZ_VER_MINOR; + version_made_by |= (MZ_PLATFORM << 8); + memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_MADE_BY_OFS, version_made_by); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); @@ -4201,41 +5678,57 @@ static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_ return MZ_TRUE; } -static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) -{ +static mz_bool mz_zip_writer_add_to_central_dir( + mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, + const void *pExtra, mz_uint16 extra_size, const void *pComment, + mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, + mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, + mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, + mz_uint32 ext_attributes) { mz_zip_internal_state *pState = pZip->m_pState; mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; size_t orig_central_dir_size = pState->m_central_dir.m_size; mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; // No zip64 support yet - if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF)) + if ((local_header_ofs > 0xFFFFFFFF) || + (((mz_uint64)pState->m_central_dir.m_size + + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + + comment_size) > 0xFFFFFFFF)) return MZ_FALSE; - if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) + if (!mz_zip_writer_create_central_dir_header( + pZip, central_dir_header, filename_size, extra_size, comment_size, + uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, + dos_date, local_header_ofs, ext_attributes)) return MZ_FALSE; - if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || - (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || - (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || - (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || - (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, ¢ral_dir_ofs, 1))) - { + if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, + filename_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, + extra_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, + comment_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, + ¢ral_dir_ofs, 1))) { // Try to push the central directory array back into its original state. - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, + MZ_FALSE); return MZ_FALSE; } return MZ_TRUE; } -static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) -{ - // Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. +static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) { + // Basic ZIP archive filename validity checks: Valid filenames cannot start + // with a forward slash, cannot contain a drive letter, and cannot use + // DOS-style backward slashes. if (*pArchive_name == '/') return MZ_FALSE; - while (*pArchive_name) - { + while (*pArchive_name) { if ((*pArchive_name == '\\') || (*pArchive_name == ':')) return MZ_FALSE; pArchive_name++; @@ -4243,33 +5736,39 @@ static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) return MZ_TRUE; } -static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) -{ +static mz_uint +mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) { mz_uint32 n; if (!pZip->m_file_offset_alignment) return 0; n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); - return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1); + return (pZip->m_file_offset_alignment - n) & + (pZip->m_file_offset_alignment - 1); } -static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) -{ +static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, + mz_uint64 cur_file_ofs, mz_uint32 n) { char buf[4096]; memset(buf, 0, MZ_MIN(sizeof(buf), n)); - while (n) - { + while (n) { mz_uint32 s = MZ_MIN(sizeof(buf), n); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) return MZ_FALSE; - cur_file_ofs += s; n -= s; + cur_file_ofs += s; + n -= s; } return MZ_TRUE; } -mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) -{ +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, + const char *pArchive_name, const void *pBuf, + size_t buf_size, const void *pComment, + mz_uint16 comment_size, + mz_uint level_and_flags, mz_uint64 uncomp_size, + mz_uint32 uncomp_crc32) { + mz_uint32 ext_attributes = 0; mz_uint16 method = 0, dos_time = 0, dos_date = 0; - mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; + mz_uint level, num_alignment_padding_bytes; mz_uint64 local_dir_header_ofs, cur_archive_file_ofs, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; @@ -4280,9 +5779,13 @@ mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; - store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); + store_data_uncompressed = + ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); - if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION)) + if ((!pZip) || (!pZip->m_pState) || + (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || + (!pArchive_name) || ((comment_size) && (!pComment)) || + (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION)) return MZ_FALSE; local_dir_header_ofs = cur_archive_file_ofs = pZip->m_archive_size; @@ -4298,8 +5801,9 @@ mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name #ifndef MINIZ_NO_TIME { - time_t cur_time; time(&cur_time); - mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date); + time_t cur_time; + time(&cur_time); + mz_zip_time_t_to_dos_time(cur_time, &dos_time, &dos_date); } #endif // #ifndef MINIZ_NO_TIME @@ -4307,14 +5811,17 @@ mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name if (archive_name_size > 0xFFFF) return MZ_FALSE; - num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + num_alignment_padding_bytes = + mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet - if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) + if ((pZip->m_total_files == 0xFFFF) || + ((pZip->m_archive_size + num_alignment_padding_bytes + + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; - if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) - { + if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) { // Set DOS Subdirectory attribute bit. ext_attributes |= 0x10; // Subdirectories cannot contain data. @@ -4322,48 +5829,56 @@ mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name return MZ_FALSE; } - // Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) - if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) + // Try to do any allocations before writing to the archive, so if an + // allocation fails the file remains unmodified. (A good idea if we're doing + // an in-place modification.) + if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + archive_name_size + comment_size)) || + (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) return MZ_FALSE; - if ((!store_data_uncompressed) && (buf_size)) - { - if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) + if ((!store_data_uncompressed) && (buf_size)) { + if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc( + pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) return MZ_FALSE; } - if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) - { + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, + num_alignment_padding_bytes + + sizeof(local_dir_header))) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; - if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } - cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); + if (pZip->m_file_offset_alignment) { + MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == + 0); + } + cur_archive_file_ofs += + num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) - { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, + archive_name_size) != archive_name_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; - if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) - { - uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8*)pBuf, buf_size); + if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { + uncomp_crc32 = + (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size); uncomp_size = buf_size; - if (uncomp_size <= 3) - { + if (uncomp_size <= 3) { level = 0; store_data_uncompressed = MZ_TRUE; } } - if (store_data_uncompressed) - { - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) - { + if (store_data_uncompressed) { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, + buf_size) != buf_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } @@ -4373,18 +5888,19 @@ mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) method = MZ_DEFLATED; - } - else if (buf_size) - { + } else if (buf_size) { mz_zip_writer_add_state state; state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; - if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || - (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) - { + if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, + tdefl_create_comp_flags_from_zip_params( + level, -15, MZ_DEFAULT_STRATEGY)) != + TDEFL_STATUS_OKAY) || + (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != + TDEFL_STATUS_DONE)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } @@ -4402,13 +5918,19 @@ mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; - if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) + if (!mz_zip_writer_create_local_dir_header( + pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, + comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; - if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, + sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; - if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) + if (!mz_zip_writer_add_to_central_dir( + pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, + comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, + dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; @@ -4418,24 +5940,30 @@ mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name } #ifndef MINIZ_NO_STDIO -mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) -{ +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, + const char *pSrc_filename, const void *pComment, + mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint32 ext_attributes) { mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; - mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; - mz_uint64 local_dir_header_ofs, cur_archive_file_ofs, uncomp_size = 0, comp_size = 0; + mz_uint16 method = 0, dos_time = 0, dos_date = 0; + time_t file_modified_time; + mz_uint64 local_dir_header_ofs, cur_archive_file_ofs, uncomp_size = 0, + comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; MZ_FILE *pSrc_file = NULL; - if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || ( level_and_flags > MZ_UBER_COMPRESSION)) - return MZ_FALSE; - - local_dir_header_ofs = cur_archive_file_ofs = pZip->m_archive_size; - if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; + if ((!pZip) || (!pZip->m_pState) || + (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || + ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + return MZ_FALSE; + + local_dir_header_ofs = cur_archive_file_ofs = pZip->m_archive_size; + if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) @@ -4445,14 +5973,20 @@ mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, if (archive_name_size > 0xFFFF) return MZ_FALSE; - num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + num_alignment_padding_bytes = + mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet - if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) + if ((pZip->m_total_files == 0xFFFF) || + ((pZip->m_archive_size + num_alignment_padding_bytes + + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; - if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date)) + memset(&file_modified_time, 0, sizeof(file_modified_time)); + if (!mz_zip_get_file_modified_time(pSrc_filename, &file_modified_time)) return MZ_FALSE; + mz_zip_time_t_to_dos_time(file_modified_time, &dos_time, &dos_date); pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); if (!pSrc_file) @@ -4461,8 +5995,7 @@ mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, uncomp_size = MZ_FTELL64(pSrc_file); MZ_FSEEK64(pSrc_file, 0, SEEK_SET); - if (uncomp_size > 0xFFFFFFFF) - { + if (uncomp_size > 0xFFFFFFFF) { // No zip64 support yet MZ_FCLOSE(pSrc_file); return MZ_FALSE; @@ -4470,57 +6003,59 @@ mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, if (uncomp_size <= 3) level = 0; - if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) - { + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, + num_alignment_padding_bytes + + sizeof(local_dir_header))) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; - if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } - cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); + if (pZip->m_file_offset_alignment) { + MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == + 0); + } + cur_archive_file_ofs += + num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) - { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, + archive_name_size) != archive_name_size) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; - if (uncomp_size) - { + if (uncomp_size) { mz_uint64 uncomp_remaining = uncomp_size; - void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); - if (!pRead_buf) - { + void *pRead_buf = + pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); + if (!pRead_buf) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } - if (!level) - { - while (uncomp_remaining) - { + if (!level) { + while (uncomp_remaining) { mz_uint n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); - if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) - { + if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || + (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, + n) != n)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } - uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); + uncomp_crc32 = + (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); uncomp_remaining -= n; cur_archive_file_ofs += n; } comp_size = uncomp_size; - } - else - { + } else { mz_bool result = MZ_FALSE; mz_zip_writer_add_state state; - tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); - if (!pComp) - { + tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc( + pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; @@ -4530,39 +6065,41 @@ mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; - if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) - { + if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, + tdefl_create_comp_flags_from_zip_params( + level, -15, MZ_DEFAULT_STRATEGY)) != + TDEFL_STATUS_OKAY) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } - for ( ; ; ) - { - size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, MZ_ZIP_MAX_IO_BUF_SIZE); + for (;;) { + size_t in_buf_size = + (mz_uint32)MZ_MIN(uncomp_remaining, MZ_ZIP_MAX_IO_BUF_SIZE); tdefl_status status; if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) break; - uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); + uncomp_crc32 = (mz_uint32)mz_crc32( + uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); uncomp_remaining -= in_buf_size; - status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH); - if (status == TDEFL_STATUS_DONE) - { + status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, + uncomp_remaining ? TDEFL_NO_FLUSH + : TDEFL_FINISH); + if (status == TDEFL_STATUS_DONE) { result = MZ_TRUE; break; - } - else if (status != TDEFL_STATUS_OKAY) + } else if (status != TDEFL_STATUS_OKAY) break; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - if (!result) - { + if (!result) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; @@ -4577,19 +6114,26 @@ mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); } - MZ_FCLOSE(pSrc_file); pSrc_file = NULL; + MZ_FCLOSE(pSrc_file); + pSrc_file = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; - if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) + if (!mz_zip_writer_create_local_dir_header( + pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, + comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; - if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, + sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; - if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) + if (!mz_zip_writer_add_to_central_dir( + pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, + comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, + dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; @@ -4599,66 +6143,89 @@ mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, } #endif // #ifndef MINIZ_NO_STDIO -mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index) -{ +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, + mz_zip_archive *pSource_zip, + mz_uint file_index) { mz_uint n, bit_flags, num_alignment_padding_bytes; mz_uint64 comp_bytes_remaining, local_dir_header_ofs; mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; - mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + mz_uint32 + local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / + sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; size_t orig_central_dir_size; mz_zip_internal_state *pState; - void *pBuf; const mz_uint8 *pSrc_central_header; + void *pBuf; + const mz_uint8 *pSrc_central_header; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return MZ_FALSE; - if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index))) + if (NULL == + (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index))) return MZ_FALSE; pState = pZip->m_pState; - num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + num_alignment_padding_bytes = + mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet - if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) + if ((pZip->m_total_files == 0xFFFF) || + ((pZip->m_archive_size + num_alignment_padding_bytes + + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > + 0xFFFFFFFF)) return MZ_FALSE; - cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + cur_src_file_ofs = + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS); cur_dst_file_ofs = pZip->m_archive_size; - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, + pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; - if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) + if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, + num_alignment_padding_bytes)) return MZ_FALSE; cur_dst_file_ofs += num_alignment_padding_bytes; local_dir_header_ofs = cur_dst_file_ofs; - if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } + if (pZip->m_file_offset_alignment) { + MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == + 0); + } - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; - n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); - comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + comp_bytes_remaining = + n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); - if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining))))) + if (NULL == + (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, + (size_t)MZ_MAX(sizeof(mz_uint32) * 4, + MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, + comp_bytes_remaining))))) return MZ_FALSE; - while (comp_bytes_remaining) - { + while (comp_bytes_remaining) { n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining); - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) - { + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, + n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) - { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } @@ -4668,22 +6235,21 @@ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive * } bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); - if (bit_flags & 8) - { + if (bit_flags & 8) { // Copy data descriptor - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) - { + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, + sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) - { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } + // cur_src_file_ofs += n; cur_dst_file_ofs += n; } pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); @@ -4695,23 +6261,29 @@ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive * orig_central_dir_size = pState->m_central_dir.m_size; memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); - MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, + local_dir_header_ofs); + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) return MZ_FALSE; - n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) - { - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); + if (!mz_zip_array_push_back( + pZip, &pState->m_central_dir, + pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, + MZ_FALSE); return MZ_FALSE; } if (pState->m_central_dir.m_size > 0xFFFFFFFF) return MZ_FALSE; n = (mz_uint32)orig_central_dir_size; - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) - { - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, + MZ_FALSE); return MZ_FALSE; } @@ -4721,8 +6293,7 @@ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive * return MZ_TRUE; } -mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) -{ +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_uint64 central_dir_ofs, central_dir_size; mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE]; @@ -4733,31 +6304,37 @@ mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) pState = pZip->m_pState; // no zip64 support yet - if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) + if ((pZip->m_total_files > 0xFFFF) || + ((pZip->m_archive_size + pState->m_central_dir.m_size + + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; central_dir_ofs = 0; central_dir_size = 0; - if (pZip->m_total_files) - { + if (pZip->m_total_files) { // Write central directory central_dir_ofs = pZip->m_archive_size; central_dir_size = pState->m_central_dir.m_size; pZip->m_central_directory_file_ofs = central_dir_ofs; - if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) + if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, + pState->m_central_dir.m_p, + (size_t)central_dir_size) != central_dir_size) return MZ_FALSE; pZip->m_archive_size += central_dir_size; } // Write end of central directory record MZ_CLEAR_OBJ(hdr); - MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); - MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, + pZip->m_total_files); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs); - if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr)) + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, + sizeof(hdr)) != sizeof(hdr)) return MZ_FALSE; #ifndef MINIZ_NO_STDIO if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) @@ -4770,8 +6347,8 @@ mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) return MZ_TRUE; } -mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize) -{ +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, + size_t *pSize) { if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) return MZ_FALSE; if (pZip->m_pWrite != mz_zip_heap_write_func) @@ -4786,11 +6363,12 @@ mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, s return MZ_TRUE; } -mz_bool mz_zip_writer_end(mz_zip_archive *pZip) -{ +mz_bool mz_zip_writer_end(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_bool status = MZ_TRUE; - if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || + ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && + (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) return MZ_FALSE; pState = pZip->m_pState; @@ -4800,15 +6378,13 @@ mz_bool mz_zip_writer_end(mz_zip_archive *pZip) mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO - if (pState->m_pFile) - { + if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO - if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) - { + if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); pState->m_pMem = NULL; } @@ -4819,44 +6395,48 @@ mz_bool mz_zip_writer_end(mz_zip_archive *pZip) } #ifndef MINIZ_NO_STDIO -mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) -{ +mz_bool mz_zip_add_mem_to_archive_file_in_place( + const char *pZip_filename, const char *pArchive_name, const void *pBuf, + size_t buf_size, const void *pComment, mz_uint16 comment_size, + mz_uint level_and_flags) { mz_bool status, created_new_archive = MZ_FALSE; mz_zip_archive zip_archive; struct MZ_FILE_STAT_STRUCT file_stat; MZ_CLEAR_OBJ(zip_archive); if ((int)level_and_flags < 0) - level_and_flags = MZ_DEFAULT_LEVEL; - if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) + level_and_flags = MZ_DEFAULT_LEVEL; + if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || + ((comment_size) && (!pComment)) || + ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; - if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) - { + if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) { // Create a new archive. if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0)) return MZ_FALSE; created_new_archive = MZ_TRUE; - } - else - { + } else { // Append to an existing archive. - if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) + if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, + level_and_flags | + MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return MZ_FALSE; - if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) - { + if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) { mz_zip_reader_end(&zip_archive); return MZ_FALSE; } } - status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); - // Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) + status = + mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, + pComment, comment_size, level_and_flags, 0, 0); + // Always finalize, even if adding failed for some reason, so we have a valid + // central directory. (This may not always succeed, but we can try.) if (!mz_zip_writer_finalize_archive(&zip_archive)) status = MZ_FALSE; if (!mz_zip_writer_end(&zip_archive)) status = MZ_FALSE; - if ((!status) && (created_new_archive)) - { + if ((!status) && (created_new_archive)) { // It's a new archive and something went wrong, so just delete it. int ignoredStatus = MZ_DELETE_FILE(pZip_filename); (void)ignoredStatus; @@ -4864,8 +6444,9 @@ mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const return status; } -void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) -{ +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, + const char *pArchive_name, + size_t *pSize, mz_uint flags) { int file_index; mz_zip_archive zip_archive; void *p = NULL; @@ -4877,10 +6458,13 @@ void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char return NULL; MZ_CLEAR_OBJ(zip_archive); - if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) + if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, + flags | + MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return NULL; - if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0) + if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, + flags)) >= 0) p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); mz_zip_reader_end(&zip_archive); diff --git a/third_party/libassimp/contrib/zip/src/zip.c b/third_party/libassimp/contrib/zip/src/zip.c index 80573096b1..ff3a8fe1e6 100644 --- a/third_party/libassimp/contrib/zip/src/zip.c +++ b/third_party/libassimp/contrib/zip/src/zip.c @@ -7,29 +7,40 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ - -#include "zip.h" -#include "miniz.h" +#define __STDC_WANT_LIB_EXT1__ 1 #include #include #include -#if defined _WIN32 || defined __WIN32__ -/* Win32, DOS */ +#if defined(_WIN32) || defined(__WIN32__) || defined(_MSC_VER) || \ + defined(__MINGW32__) +/* Win32, DOS, MSVC, MSVS */ #include #define MKDIR(DIRNAME) _mkdir(DIRNAME) #define STRCLONE(STR) ((STR) ? _strdup(STR) : NULL) #define HAS_DEVICE(P) \ - ((((P)[0] >= 'A' && (P)[0] <= 'Z') || ((P)[0] >= 'a' && (P)[0] <= 'z')) && \ - (P)[1] == ':') + ((((P)[0] >= 'A' && (P)[0] <= 'Z') || ((P)[0] >= 'a' && (P)[0] <= 'z')) && \ + (P)[1] == ':') #define FILESYSTEM_PREFIX_LEN(P) (HAS_DEVICE(P) ? 2 : 0) #define ISSLASH(C) ((C) == '/' || (C) == '\\') #else + +#include // needed for symlink() on BSD +int symlink(const char *target, const char *linkpath); // needed on Linux + #define MKDIR(DIRNAME) mkdir(DIRNAME, 0755) #define STRCLONE(STR) ((STR) ? strdup(STR) : NULL) + +#endif + +#include "miniz.h" +#include "zip.h" + +#ifndef HAS_DEVICE +#define HAS_DEVICE(P) 0 #endif #ifndef FILESYSTEM_PREFIX_LEN @@ -40,601 +51,876 @@ #define ISSLASH(C) ((C) == '/') #endif -#define CLEANUP(ptr) \ - do { \ - if (ptr) { \ - free((void *)ptr); \ - ptr = NULL; \ - } \ - } while (0) +#define CLEANUP(ptr) \ + do { \ + if (ptr) { \ + free((void *)ptr); \ + ptr = NULL; \ + } \ + } while (0) -static char *basename(const char *name) { - char const *p; - char const *base = name += FILESYSTEM_PREFIX_LEN(name); - int all_slashes = 1; +static const char *base_name(const char *name) { + char const *p; + char const *base = name += FILESYSTEM_PREFIX_LEN(name); + int all_slashes = 1; - for (p = name; *p; p++) { - if (ISSLASH(*p)) - base = p + 1; - else - all_slashes = 0; - } + for (p = name; *p; p++) { + if (ISSLASH(*p)) + base = p + 1; + else + all_slashes = 0; + } - /* If NAME is all slashes, arrange to return `/'. */ - if (*base == '\0' && ISSLASH(*name) && all_slashes) --base; + /* If NAME is all slashes, arrange to return `/'. */ + if (*base == '\0' && ISSLASH(*name) && all_slashes) + --base; - return (char *)base; + return base; } static int mkpath(const char *path) { - char const *p; - char npath[MAX_PATH + 1] = {0}; - int len = 0; + char const *p; + char npath[MAX_PATH + 1]; + int len = 0; + int has_device = HAS_DEVICE(path); - for (p = path; *p && len < MAX_PATH; p++) { - if (ISSLASH(*p) && len > 0) { - if (MKDIR(npath) == -1) - if (errno != EEXIST) return -1; - } - npath[len++] = *p; + memset(npath, 0, MAX_PATH + 1); + +#ifdef _WIN32 + // only on windows fix the path + npath[0] = path[0]; + npath[1] = path[1]; + len = 2; +#endif // _WIN32 + + for (p = path + len; *p && len < MAX_PATH; p++) { + if (ISSLASH(*p) && ((!has_device && len > 0) || (has_device && len > 2))) { + if (MKDIR(npath) == -1) + if (errno != EEXIST) + return -1; } + npath[len++] = *p; + } - return 0; + return 0; } -static char *strrpl(const char *str, char oldchar, char newchar) { - char *rpl = (char *)malloc(sizeof(char) * (1 + strlen(str))); - char *begin = rpl; - char c; - while((c = *str++)) { - if (c == oldchar) { - c = newchar; - } - *rpl++ = c; - } - *rpl = '\0'; +static char *strrpl(const char *str, size_t n, char oldchar, char newchar) { + char c; + size_t i; + char *rpl = (char *)calloc((1 + n), sizeof(char)); + char *begin = rpl; + if (!rpl) { + return NULL; + } - return begin; + for (i = 0; (i < n) && (c = *str++); ++i) { + if (c == oldchar) { + c = newchar; + } + *rpl++ = c; + } + + return begin; } struct zip_entry_t { - int index; - const char *name; - mz_uint64 uncomp_size; - mz_uint64 comp_size; - mz_uint32 uncomp_crc32; - mz_uint64 offset; - mz_uint8 header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; - mz_uint64 header_offset; - mz_uint16 method; - mz_zip_writer_add_state state; - tdefl_compressor comp; + int index; + char *name; + mz_uint64 uncomp_size; + mz_uint64 comp_size; + mz_uint32 uncomp_crc32; + mz_uint64 offset; + mz_uint8 header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + mz_uint64 header_offset; + mz_uint16 method; + mz_zip_writer_add_state state; + tdefl_compressor comp; + mz_uint32 external_attr; + time_t m_time; }; struct zip_t { - mz_zip_archive archive; - mz_uint level; - struct zip_entry_t entry; - char mode; + mz_zip_archive archive; + mz_uint level; + struct zip_entry_t entry; }; struct zip_t *zip_open(const char *zipname, int level, char mode) { - struct zip_t *zip = NULL; + struct zip_t *zip = NULL; - if (!zipname || strlen(zipname) < 1) { - // zip_t archive name is empty or NULL - goto cleanup; + if (!zipname || strlen(zipname) < 1) { + // zip_t archive name is empty or NULL + goto cleanup; + } + + if (level < 0) + level = MZ_DEFAULT_LEVEL; + if ((level & 0xF) > MZ_UBER_COMPRESSION) { + // Wrong compression level + goto cleanup; + } + + zip = (struct zip_t *)calloc((size_t)1, sizeof(struct zip_t)); + if (!zip) + goto cleanup; + + zip->level = (mz_uint)level; + switch (mode) { + case 'w': + // Create a new archive. + if (!mz_zip_writer_init_file(&(zip->archive), zipname, 0)) { + // Cannot initialize zip_archive writer + goto cleanup; } + break; - if (level < 0) level = MZ_DEFAULT_LEVEL; - if ((level & 0xF) > MZ_UBER_COMPRESSION) { - // Wrong compression level - goto cleanup; + case 'r': + case 'a': + if (!mz_zip_reader_init_file( + &(zip->archive), zipname, + zip->level | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) { + // An archive file does not exist or cannot initialize + // zip_archive reader + goto cleanup; } - - zip = (struct zip_t *)calloc((size_t)1, sizeof(struct zip_t)); - if (!zip) goto cleanup; - - zip->level = level; - zip->mode = mode; - switch (mode) { - case 'w': - // Create a new archive. - if (!mz_zip_writer_init_file(&(zip->archive), zipname, 0)) { - // Cannot initialize zip_archive writer - goto cleanup; - } - break; - - case 'r': - case 'a': - if (!mz_zip_reader_init_file( - &(zip->archive), zipname, - level | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) { - // An archive file does not exist or cannot initialize - // zip_archive reader - goto cleanup; - } - - if (mode == 'a' && - !mz_zip_writer_init_from_reader(&(zip->archive), zipname)) { - mz_zip_reader_end(&(zip->archive)); - goto cleanup; - } - - break; - - default: - goto cleanup; + if (mode == 'a' && + !mz_zip_writer_init_from_reader(&(zip->archive), zipname)) { + mz_zip_reader_end(&(zip->archive)); + goto cleanup; } + break; - return zip; + default: + goto cleanup; + } + + return zip; cleanup: - CLEANUP(zip); - return NULL; + CLEANUP(zip); + return NULL; } void zip_close(struct zip_t *zip) { - if (zip) { - // Always finalize, even if adding failed for some reason, so we have a - // valid central directory. - mz_zip_writer_finalize_archive(&(zip->archive)); + if (zip) { + // Always finalize, even if adding failed for some reason, so we have a + // valid central directory. + mz_zip_writer_finalize_archive(&(zip->archive)); - mz_zip_writer_end(&(zip->archive)); - mz_zip_reader_end(&(zip->archive)); + mz_zip_writer_end(&(zip->archive)); + mz_zip_reader_end(&(zip->archive)); - CLEANUP(zip); - } + CLEANUP(zip); + } } int zip_entry_open(struct zip_t *zip, const char *entryname) { - char *locname = NULL; - size_t entrylen = 0; - mz_zip_archive *pzip = NULL; - mz_uint num_alignment_padding_bytes, level; + size_t entrylen = 0; + mz_zip_archive *pzip = NULL; + mz_uint num_alignment_padding_bytes, level; + mz_zip_archive_file_stat stats; - if (!zip || !entryname) { - return -1; + if (!zip || !entryname) { + return -1; + } + + entrylen = strlen(entryname); + if (entrylen < 1) { + return -1; + } + + /* + .ZIP File Format Specification Version: 6.3.3 + + 4.4.17.1 The name of the file, with optional relative path. + The path stored MUST not contain a drive or + device letter, or a leading slash. All slashes + MUST be forward slashes '/' as opposed to + backwards slashes '\' for compatibility with Amiga + and UNIX file systems etc. If input came from standard + input, there is no file name field. + */ + zip->entry.name = strrpl(entryname, entrylen, '\\', '/'); + if (!zip->entry.name) { + // Cannot parse zip entry name + return -1; + } + + pzip = &(zip->archive); + if (pzip->m_zip_mode == MZ_ZIP_MODE_READING) { + zip->entry.index = + mz_zip_reader_locate_file(pzip, zip->entry.name, NULL, 0); + if (zip->entry.index < 0) { + goto cleanup; } - entrylen = strlen(entryname); - if (entrylen < 1) { - return -1; + if (!mz_zip_reader_file_stat(pzip, (mz_uint)zip->entry.index, &stats)) { + goto cleanup; } - pzip = &(zip->archive); - /* - .ZIP File Format Specification Version: 6.3.3 - - 4.4.17.1 The name of the file, with optional relative path. - The path stored MUST not contain a drive or - device letter, or a leading slash. All slashes - MUST be forward slashes '/' as opposed to - backwards slashes '\' for compatibility with Amiga - and UNIX file systems etc. If input came from standard - input, there is no file name field. - */ - locname = strrpl(entryname, '\\', '/'); - - if (zip->mode == 'r') { - zip->entry.index = mz_zip_reader_locate_file(pzip, locname, NULL, 0); - CLEANUP(locname); - return (zip->entry.index < 0) ? -1 : 0; - } - - zip->entry.index = zip->archive.m_total_files; - zip->entry.name = locname; - if (!zip->entry.name) { - // Cannot parse zip entry name - return -1; - } - - zip->entry.comp_size = 0; - zip->entry.uncomp_size = 0; - zip->entry.uncomp_crc32 = MZ_CRC32_INIT; - zip->entry.offset = zip->archive.m_archive_size; - zip->entry.header_offset = zip->archive.m_archive_size; - memset(zip->entry.header, 0, - MZ_ZIP_LOCAL_DIR_HEADER_SIZE * sizeof(mz_uint8)); - zip->entry.method = 0; - - num_alignment_padding_bytes = - mz_zip_writer_compute_padding_needed_for_file_alignment(pzip); - - if (!pzip->m_pState || (pzip->m_zip_mode != MZ_ZIP_MODE_WRITING)) { - // Wrong zip mode - return -1; - } - if (zip->level & MZ_ZIP_FLAG_COMPRESSED_DATA) { - // Wrong zip compression level - return -1; - } - // no zip64 support yet - if ((pzip->m_total_files == 0xFFFF) || - ((pzip->m_archive_size + num_alignment_padding_bytes + - MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + - entrylen) > 0xFFFFFFFF)) { - // No zip64 support yet - return -1; - } - if (!mz_zip_writer_write_zeros( - pzip, zip->entry.offset, - num_alignment_padding_bytes + sizeof(zip->entry.header))) { - // Cannot memset zip entry header - return -1; - } - - zip->entry.header_offset += num_alignment_padding_bytes; - if (pzip->m_file_offset_alignment) { - MZ_ASSERT((zip->entry.header_offset & - (pzip->m_file_offset_alignment - 1)) == 0); - } - zip->entry.offset += - num_alignment_padding_bytes + sizeof(zip->entry.header); - - if (pzip->m_pWrite(pzip->m_pIO_opaque, zip->entry.offset, zip->entry.name, - entrylen) != entrylen) { - // Cannot write data to zip entry - return -1; - } - - zip->entry.offset += entrylen; - level = zip->level & 0xF; - if (level) { - zip->entry.state.m_pZip = pzip; - zip->entry.state.m_cur_archive_file_ofs = zip->entry.offset; - zip->entry.state.m_comp_size = 0; - - if (tdefl_init(&(zip->entry.comp), mz_zip_writer_add_put_buf_callback, - &(zip->entry.state), - tdefl_create_comp_flags_from_zip_params( - level, -15, MZ_DEFAULT_STRATEGY)) != - TDEFL_STATUS_OKAY) { - // Cannot initialize the zip compressor - return -1; - } - } + zip->entry.comp_size = stats.m_comp_size; + zip->entry.uncomp_size = stats.m_uncomp_size; + zip->entry.uncomp_crc32 = stats.m_crc32; + zip->entry.offset = stats.m_central_dir_ofs; + zip->entry.header_offset = stats.m_local_header_ofs; + zip->entry.method = stats.m_method; + zip->entry.external_attr = stats.m_external_attr; + zip->entry.m_time = stats.m_time; return 0; + } + + zip->entry.index = (int)zip->archive.m_total_files; + zip->entry.comp_size = 0; + zip->entry.uncomp_size = 0; + zip->entry.uncomp_crc32 = MZ_CRC32_INIT; + zip->entry.offset = zip->archive.m_archive_size; + zip->entry.header_offset = zip->archive.m_archive_size; + memset(zip->entry.header, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE * sizeof(mz_uint8)); + zip->entry.method = 0; + zip->entry.external_attr = 0; + + num_alignment_padding_bytes = + mz_zip_writer_compute_padding_needed_for_file_alignment(pzip); + + if (!pzip->m_pState || (pzip->m_zip_mode != MZ_ZIP_MODE_WRITING)) { + // Wrong zip mode + goto cleanup; + } + if (zip->level & MZ_ZIP_FLAG_COMPRESSED_DATA) { + // Wrong zip compression level + goto cleanup; + } + // no zip64 support yet + if ((pzip->m_total_files == 0xFFFF) || + ((pzip->m_archive_size + num_alignment_padding_bytes + + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + entrylen) > 0xFFFFFFFF)) { + // No zip64 support yet + goto cleanup; + } + if (!mz_zip_writer_write_zeros(pzip, zip->entry.offset, + num_alignment_padding_bytes + + sizeof(zip->entry.header))) { + // Cannot memset zip entry header + goto cleanup; + } + + zip->entry.header_offset += num_alignment_padding_bytes; + if (pzip->m_file_offset_alignment) { + MZ_ASSERT( + (zip->entry.header_offset & (pzip->m_file_offset_alignment - 1)) == 0); + } + zip->entry.offset += num_alignment_padding_bytes + sizeof(zip->entry.header); + + if (pzip->m_pWrite(pzip->m_pIO_opaque, zip->entry.offset, zip->entry.name, + entrylen) != entrylen) { + // Cannot write data to zip entry + goto cleanup; + } + + zip->entry.offset += entrylen; + level = zip->level & 0xF; + if (level) { + zip->entry.state.m_pZip = pzip; + zip->entry.state.m_cur_archive_file_ofs = zip->entry.offset; + zip->entry.state.m_comp_size = 0; + + if (tdefl_init(&(zip->entry.comp), mz_zip_writer_add_put_buf_callback, + &(zip->entry.state), + (int)tdefl_create_comp_flags_from_zip_params( + (int)level, -15, MZ_DEFAULT_STRATEGY)) != + TDEFL_STATUS_OKAY) { + // Cannot initialize the zip compressor + goto cleanup; + } + } + + zip->entry.m_time = time(NULL); + + return 0; + +cleanup: + CLEANUP(zip->entry.name); + return -1; +} + +int zip_entry_openbyindex(struct zip_t *zip, int index) { + mz_zip_archive *pZip = NULL; + mz_zip_archive_file_stat stats; + mz_uint namelen; + const mz_uint8 *pHeader; + const char *pFilename; + + if (!zip) { + // zip_t handler is not initialized + return -1; + } + + pZip = &(zip->archive); + if (pZip->m_zip_mode != MZ_ZIP_MODE_READING) { + // open by index requires readonly mode + return -1; + } + + if (index < 0 || (mz_uint)index >= pZip->m_total_files) { + // index out of range + return -1; + } + + if (!(pHeader = &MZ_ZIP_ARRAY_ELEMENT( + &pZip->m_pState->m_central_dir, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, + mz_uint32, index)))) { + // cannot find header in central directory + return -1; + } + + namelen = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); + pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + + /* + .ZIP File Format Specification Version: 6.3.3 + + 4.4.17.1 The name of the file, with optional relative path. + The path stored MUST not contain a drive or + device letter, or a leading slash. All slashes + MUST be forward slashes '/' as opposed to + backwards slashes '\' for compatibility with Amiga + and UNIX file systems etc. If input came from standard + input, there is no file name field. + */ + zip->entry.name = strrpl(pFilename, namelen, '\\', '/'); + if (!zip->entry.name) { + // local entry name is NULL + return -1; + } + + if (!mz_zip_reader_file_stat(pZip, (mz_uint)index, &stats)) { + return -1; + } + + zip->entry.index = index; + zip->entry.comp_size = stats.m_comp_size; + zip->entry.uncomp_size = stats.m_uncomp_size; + zip->entry.uncomp_crc32 = stats.m_crc32; + zip->entry.offset = stats.m_central_dir_ofs; + zip->entry.header_offset = stats.m_local_header_ofs; + zip->entry.method = stats.m_method; + zip->entry.external_attr = stats.m_external_attr; + zip->entry.m_time = stats.m_time; + + return 0; } int zip_entry_close(struct zip_t *zip) { - mz_zip_archive *pzip = NULL; - mz_uint level; - tdefl_status done; - mz_uint16 entrylen; - time_t t; - struct tm *tm; - mz_uint16 dos_time, dos_date; - int status = -1; + mz_zip_archive *pzip = NULL; + mz_uint level; + tdefl_status done; + mz_uint16 entrylen; + mz_uint16 dos_time, dos_date; + int status = -1; - if (!zip) { - // zip_t handler is not initialized - return -1; - } + if (!zip) { + // zip_t handler is not initialized + goto cleanup; + } - if (zip->mode == 'r') { - return 0; - } - - pzip = &(zip->archive); - level = zip->level & 0xF; - if (level) { - done = tdefl_compress_buffer(&(zip->entry.comp), "", 0, TDEFL_FINISH); - if (done != TDEFL_STATUS_DONE && done != TDEFL_STATUS_OKAY) { - // Cannot flush compressed buffer - goto cleanup; - } - zip->entry.comp_size = zip->entry.state.m_comp_size; - zip->entry.offset = zip->entry.state.m_cur_archive_file_ofs; - zip->entry.method = MZ_DEFLATED; - } - - entrylen = (mz_uint16)strlen(zip->entry.name); - t = time(NULL); - tm = localtime(&t); - dos_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + - ((tm->tm_sec) >> 1)); - dos_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + - ((tm->tm_mon + 1) << 5) + tm->tm_mday); - - // no zip64 support yet - if ((zip->entry.comp_size > 0xFFFFFFFF) || - (zip->entry.offset > 0xFFFFFFFF)) { - // No zip64 support, yet - goto cleanup; - } - - if (!mz_zip_writer_create_local_dir_header( - pzip, zip->entry.header, entrylen, 0, zip->entry.uncomp_size, - zip->entry.comp_size, zip->entry.uncomp_crc32, zip->entry.method, 0, - dos_time, dos_date)) { - // Cannot create zip entry header - goto cleanup; - } - - if (pzip->m_pWrite(pzip->m_pIO_opaque, zip->entry.header_offset, - zip->entry.header, sizeof(zip->entry.header)) != - sizeof(zip->entry.header)) { - // Cannot write zip entry header - goto cleanup; - } - - if (!mz_zip_writer_add_to_central_dir( - pzip, zip->entry.name, entrylen, NULL, 0, "", 0, - zip->entry.uncomp_size, zip->entry.comp_size, - zip->entry.uncomp_crc32, zip->entry.method, 0, dos_time, dos_date, - zip->entry.header_offset, 0)) { - // Cannot write to zip central dir - goto cleanup; - } - - pzip->m_total_files++; - pzip->m_archive_size = zip->entry.offset; + pzip = &(zip->archive); + if (pzip->m_zip_mode == MZ_ZIP_MODE_READING) { status = 0; + goto cleanup; + } + + level = zip->level & 0xF; + if (level) { + done = tdefl_compress_buffer(&(zip->entry.comp), "", 0, TDEFL_FINISH); + if (done != TDEFL_STATUS_DONE && done != TDEFL_STATUS_OKAY) { + // Cannot flush compressed buffer + goto cleanup; + } + zip->entry.comp_size = zip->entry.state.m_comp_size; + zip->entry.offset = zip->entry.state.m_cur_archive_file_ofs; + zip->entry.method = MZ_DEFLATED; + } + + entrylen = (mz_uint16)strlen(zip->entry.name); + // no zip64 support yet + if ((zip->entry.comp_size > 0xFFFFFFFF) || (zip->entry.offset > 0xFFFFFFFF)) { + // No zip64 support, yet + goto cleanup; + } + + mz_zip_time_t_to_dos_time(zip->entry.m_time, &dos_time, &dos_date); + if (!mz_zip_writer_create_local_dir_header( + pzip, zip->entry.header, entrylen, 0, zip->entry.uncomp_size, + zip->entry.comp_size, zip->entry.uncomp_crc32, zip->entry.method, 0, + dos_time, dos_date)) { + // Cannot create zip entry header + goto cleanup; + } + + if (pzip->m_pWrite(pzip->m_pIO_opaque, zip->entry.header_offset, + zip->entry.header, + sizeof(zip->entry.header)) != sizeof(zip->entry.header)) { + // Cannot write zip entry header + goto cleanup; + } + + if (!mz_zip_writer_add_to_central_dir( + pzip, zip->entry.name, entrylen, NULL, 0, "", 0, + zip->entry.uncomp_size, zip->entry.comp_size, zip->entry.uncomp_crc32, + zip->entry.method, 0, dos_time, dos_date, zip->entry.header_offset, + zip->entry.external_attr)) { + // Cannot write to zip central dir + goto cleanup; + } + + pzip->m_total_files++; + pzip->m_archive_size = zip->entry.offset; + status = 0; cleanup: + if (zip) { + zip->entry.m_time = 0; CLEANUP(zip->entry.name); - return status; + } + return status; +} + +const char *zip_entry_name(struct zip_t *zip) { + if (!zip) { + // zip_t handler is not initialized + return NULL; + } + + return zip->entry.name; +} + +int zip_entry_index(struct zip_t *zip) { + if (!zip) { + // zip_t handler is not initialized + return -1; + } + + return zip->entry.index; +} + +int zip_entry_isdir(struct zip_t *zip) { + if (!zip) { + // zip_t handler is not initialized + return -1; + } + + if (zip->entry.index < 0) { + // zip entry is not opened + return -1; + } + + return (int)mz_zip_reader_is_file_a_directory(&zip->archive, + (mz_uint)zip->entry.index); +} + +unsigned long long zip_entry_size(struct zip_t *zip) { + return zip ? zip->entry.uncomp_size : 0; +} + +unsigned int zip_entry_crc32(struct zip_t *zip) { + return zip ? zip->entry.uncomp_crc32 : 0; } int zip_entry_write(struct zip_t *zip, const void *buf, size_t bufsize) { - mz_uint level; - mz_zip_archive *pzip = NULL; - tdefl_status status; + mz_uint level; + mz_zip_archive *pzip = NULL; + tdefl_status status; - if (!zip) { - // zip_t handler is not initialized + if (!zip) { + // zip_t handler is not initialized + return -1; + } + + pzip = &(zip->archive); + if (buf && bufsize > 0) { + zip->entry.uncomp_size += bufsize; + zip->entry.uncomp_crc32 = (mz_uint32)mz_crc32( + zip->entry.uncomp_crc32, (const mz_uint8 *)buf, bufsize); + + level = zip->level & 0xF; + if (!level) { + if ((pzip->m_pWrite(pzip->m_pIO_opaque, zip->entry.offset, buf, + bufsize) != bufsize)) { + // Cannot write buffer return -1; + } + zip->entry.offset += bufsize; + zip->entry.comp_size += bufsize; + } else { + status = tdefl_compress_buffer(&(zip->entry.comp), buf, bufsize, + TDEFL_NO_FLUSH); + if (status != TDEFL_STATUS_DONE && status != TDEFL_STATUS_OKAY) { + // Cannot compress buffer + return -1; + } } + } - pzip = &(zip->archive); - if (buf && bufsize > 0) { - zip->entry.uncomp_size += bufsize; - zip->entry.uncomp_crc32 = (mz_uint32)mz_crc32( - zip->entry.uncomp_crc32, (const mz_uint8 *)buf, bufsize); - - level = zip->level & 0xF; - if (!level) { - if ((pzip->m_pWrite(pzip->m_pIO_opaque, zip->entry.offset, buf, - bufsize) != bufsize)) { - // Cannot write buffer - return -1; - } - zip->entry.offset += bufsize; - zip->entry.comp_size += bufsize; - } else { - status = tdefl_compress_buffer(&(zip->entry.comp), buf, bufsize, - TDEFL_NO_FLUSH); - if (status != TDEFL_STATUS_DONE && status != TDEFL_STATUS_OKAY) { - // Cannot compress buffer - return -1; - } - } - } - - return 0; + return 0; } int zip_entry_fwrite(struct zip_t *zip, const char *filename) { - int status = 0; - size_t n = 0; - FILE *stream = NULL; - mz_uint8 buf[MZ_ZIP_MAX_IO_BUF_SIZE] = {0}; + int status = 0; + size_t n = 0; + FILE *stream = NULL; + mz_uint8 buf[MZ_ZIP_MAX_IO_BUF_SIZE]; + struct MZ_FILE_STAT_STRUCT file_stat; - if (!zip) { - // zip_t handler is not initialized - return -1; + if (!zip) { + // zip_t handler is not initialized + return -1; + } + + memset(buf, 0, MZ_ZIP_MAX_IO_BUF_SIZE); + memset((void *)&file_stat, 0, sizeof(struct MZ_FILE_STAT_STRUCT)); + if (MZ_FILE_STAT(filename, &file_stat) != 0) { + // problem getting information - check errno + return -1; + } + + if ((file_stat.st_mode & 0200) == 0) { + // MS-DOS read-only attribute + zip->entry.external_attr |= 0x01; + } + zip->entry.external_attr |= (mz_uint32)((file_stat.st_mode & 0xFFFF) << 16); + zip->entry.m_time = file_stat.st_mtime; + +#if defined(_MSC_VER) + if (fopen_s(&stream, filename, "rb")) +#else + if (!(stream = fopen(filename, "rb"))) +#endif + { + // Cannot open filename + return -1; + } + + while ((n = fread(buf, sizeof(mz_uint8), MZ_ZIP_MAX_IO_BUF_SIZE, stream)) > + 0) { + if (zip_entry_write(zip, buf, n) < 0) { + status = -1; + break; } + } + fclose(stream); - stream = fopen(filename, "rb"); - if (!stream) { - // Cannot open filename - return -1; - } - - while ((n = fread(buf, sizeof(mz_uint8), MZ_ZIP_MAX_IO_BUF_SIZE, stream)) > - 0) { - if (zip_entry_write(zip, buf, n) < 0) { - status = -1; - break; - } - } - fclose(stream); - - return status; + return status; } -int zip_entry_read(struct zip_t *zip, void **buf, size_t *bufsize) { - mz_zip_archive *pzip = NULL; - mz_uint idx; +ssize_t zip_entry_read(struct zip_t *zip, void **buf, size_t *bufsize) { + mz_zip_archive *pzip = NULL; + mz_uint idx; + size_t size = 0; - if (!zip) { - // zip_t handler is not initialized - return -1; - } + if (!zip) { + // zip_t handler is not initialized + return -1; + } - if (zip->mode != 'r' || zip->entry.index < 0) { - // the entry is not found or we do not have read access - return -1; - } + pzip = &(zip->archive); + if (pzip->m_zip_mode != MZ_ZIP_MODE_READING || zip->entry.index < 0) { + // the entry is not found or we do not have read access + return -1; + } - pzip = &(zip->archive); - idx = (mz_uint)zip->entry.index; - if (mz_zip_reader_is_file_a_directory(pzip, idx)) { - // the entry is a directory - return -1; - } + idx = (mz_uint)zip->entry.index; + if (mz_zip_reader_is_file_a_directory(pzip, idx)) { + // the entry is a directory + return -1; + } - *buf = mz_zip_reader_extract_to_heap(pzip, idx, bufsize, 0); - return (*buf) ? 0 : -1; + *buf = mz_zip_reader_extract_to_heap(pzip, idx, &size, 0); + if (*buf && bufsize) { + *bufsize = size; + } + return size; +} + +ssize_t zip_entry_noallocread(struct zip_t *zip, void *buf, size_t bufsize) { + mz_zip_archive *pzip = NULL; + + if (!zip) { + // zip_t handler is not initialized + return -1; + } + + pzip = &(zip->archive); + if (pzip->m_zip_mode != MZ_ZIP_MODE_READING || zip->entry.index < 0) { + // the entry is not found or we do not have read access + return -1; + } + + if (!mz_zip_reader_extract_to_mem_no_alloc(pzip, (mz_uint)zip->entry.index, + buf, bufsize, 0, NULL, 0)) { + return -1; + } + + return (ssize_t)zip->entry.uncomp_size; } int zip_entry_fread(struct zip_t *zip, const char *filename) { - mz_zip_archive *pzip = NULL; - mz_uint idx; + mz_zip_archive *pzip = NULL; + mz_uint idx; +#if defined(_MSC_VER) +#else + mz_uint32 xattr = 0; +#endif + mz_zip_archive_file_stat info; - if (!zip) { - // zip_t handler is not initialized - return -1; + if (!zip) { + // zip_t handler is not initialized + return -1; + } + + memset((void *)&info, 0, sizeof(mz_zip_archive_file_stat)); + pzip = &(zip->archive); + if (pzip->m_zip_mode != MZ_ZIP_MODE_READING || zip->entry.index < 0) { + // the entry is not found or we do not have read access + return -1; + } + + idx = (mz_uint)zip->entry.index; + if (mz_zip_reader_is_file_a_directory(pzip, idx)) { + // the entry is a directory + return -1; + } + + if (!mz_zip_reader_extract_to_file(pzip, idx, filename, 0)) { + return -1; + } + +#if defined(_MSC_VER) +#else + if (!mz_zip_reader_file_stat(pzip, idx, &info)) { + // Cannot get information about zip archive; + return -1; + } + + xattr = (info.m_external_attr >> 16) & 0xFFFF; + if (xattr > 0) { + if (chmod(filename, (mode_t)xattr) < 0) { + return -1; } + } +#endif - if (zip->mode != 'r' || zip->entry.index < 0) { - // the entry is not found or we do not have read access - return -1; - } - - pzip = &(zip->archive); - idx = (mz_uint)zip->entry.index; - if (mz_zip_reader_is_file_a_directory(pzip, idx)) { - // the entry is a directory - return -1; - } - - return (mz_zip_reader_extract_to_file(pzip, idx, filename, 0)) ? 0 : -1; + return 0; } int zip_entry_extract(struct zip_t *zip, size_t (*on_extract)(void *arg, unsigned long long offset, const void *buf, size_t bufsize), void *arg) { - mz_zip_archive *pzip = NULL; - mz_uint idx; + mz_zip_archive *pzip = NULL; + mz_uint idx; - if (!zip) { - // zip_t handler is not initialized - return -1; - } + if (!zip) { + // zip_t handler is not initialized + return -1; + } - if (zip->mode != 'r' || zip->entry.index < 0) { - // the entry is not found or we do not have read access - return -1; - } + pzip = &(zip->archive); + if (pzip->m_zip_mode != MZ_ZIP_MODE_READING || zip->entry.index < 0) { + // the entry is not found or we do not have read access + return -1; + } - pzip = &(zip->archive); - idx = (mz_uint)zip->entry.index; + idx = (mz_uint)zip->entry.index; + return (mz_zip_reader_extract_to_callback(pzip, idx, on_extract, arg, 0)) + ? 0 + : -1; +} - return (mz_zip_reader_extract_to_callback(pzip, idx, on_extract, arg, 0)) - ? 0 - : -1; +int zip_total_entries(struct zip_t *zip) { + if (!zip) { + // zip_t handler is not initialized + return -1; + } + + return (int)zip->archive.m_total_files; } int zip_create(const char *zipname, const char *filenames[], size_t len) { - int status = 0; - size_t i; - mz_zip_archive zip_archive; + int status = 0; + size_t i; + mz_zip_archive zip_archive; + struct MZ_FILE_STAT_STRUCT file_stat; + mz_uint32 ext_attributes = 0; - if (!zipname || strlen(zipname) < 1) { - // zip_t archive name is empty or NULL - return -1; + if (!zipname || strlen(zipname) < 1) { + // zip_t archive name is empty or NULL + return -1; + } + + // Create a new archive. + if (!memset(&(zip_archive), 0, sizeof(zip_archive))) { + // Cannot memset zip archive + return -1; + } + + if (!mz_zip_writer_init_file(&zip_archive, zipname, 0)) { + // Cannot initialize zip_archive writer + return -1; + } + + memset((void *)&file_stat, 0, sizeof(struct MZ_FILE_STAT_STRUCT)); + + for (i = 0; i < len; ++i) { + const char *name = filenames[i]; + if (!name) { + status = -1; + break; } - // Create a new archive. - if (!memset(&(zip_archive), 0, sizeof(zip_archive))) { - // Cannot memset zip archive - return -1; + if (MZ_FILE_STAT(name, &file_stat) != 0) { + // problem getting information - check errno + return -1; } - if (!mz_zip_writer_init_file(&zip_archive, zipname, 0)) { - // Cannot initialize zip_archive writer - return -1; + if ((file_stat.st_mode & 0200) == 0) { + // MS-DOS read-only attribute + ext_attributes |= 0x01; } + ext_attributes |= (mz_uint32)((file_stat.st_mode & 0xFFFF) << 16); - for (i = 0; i < len; ++i) { - const char *name = filenames[i]; - if (!name) { - status = -1; - break; - } - - if (!mz_zip_writer_add_file(&zip_archive, basename(name), name, "", 0, - ZIP_DEFAULT_COMPRESSION_LEVEL)) { - // Cannot add file to zip_archive - status = -1; - break; - } + if (!mz_zip_writer_add_file(&zip_archive, base_name(name), name, "", 0, + ZIP_DEFAULT_COMPRESSION_LEVEL, + ext_attributes)) { + // Cannot add file to zip_archive + status = -1; + break; } + } - mz_zip_writer_finalize_archive(&zip_archive); - mz_zip_writer_end(&zip_archive); - return status; + mz_zip_writer_finalize_archive(&zip_archive); + mz_zip_writer_end(&zip_archive); + return status; } int zip_extract(const char *zipname, const char *dir, int (*on_extract)(const char *filename, void *arg), void *arg) { - int status = -1; - mz_uint i, n; - char path[MAX_PATH + 1] = {0}; - mz_zip_archive zip_archive; - mz_zip_archive_file_stat info; - size_t dirlen = 0; + int status = -1; + mz_uint i, n; + char path[MAX_PATH + 1]; + char symlink_to[MAX_PATH + 1]; + mz_zip_archive zip_archive; + mz_zip_archive_file_stat info; + size_t dirlen = 0; + mz_uint32 xattr = 0; - if (!memset(&(zip_archive), 0, sizeof(zip_archive))) { - // Cannot memset zip archive - return -1; - } + memset(path, 0, sizeof(path)); + memset(symlink_to, 0, sizeof(symlink_to)); + if (!memset(&(zip_archive), 0, sizeof(zip_archive))) { + // Cannot memset zip archive + return -1; + } - if (!zipname || !dir) { - // Cannot parse zip archive name - return -1; - } + if (!zipname || !dir) { + // Cannot parse zip archive name + return -1; + } - dirlen = strlen(dir); - if (dirlen + 1 > MAX_PATH) { - return -1; - } + dirlen = strlen(dir); + if (dirlen + 1 > MAX_PATH) { + return -1; + } - // Now try to open the archive. - if (!mz_zip_reader_init_file(&zip_archive, zipname, 0)) { - // Cannot initialize zip_archive reader - return -1; - } + // Now try to open the archive. + if (!mz_zip_reader_init_file(&zip_archive, zipname, 0)) { + // Cannot initialize zip_archive reader + return -1; + } - strcpy(path, dir); - if (!ISSLASH(path[dirlen - 1])) { -#if defined _WIN32 || defined __WIN32__ - path[dirlen] = '\\'; + memset((void *)&info, 0, sizeof(mz_zip_archive_file_stat)); + +#if defined(_MSC_VER) + strcpy_s(path, MAX_PATH, dir); #else - path[dirlen] = '/'; + strcpy(path, dir); #endif - ++dirlen; + + if (!ISSLASH(path[dirlen - 1])) { +#if defined(_WIN32) || defined(__WIN32__) + path[dirlen] = '\\'; +#else + path[dirlen] = '/'; +#endif + ++dirlen; + } + + // Get and print information about each file in the archive. + n = mz_zip_reader_get_num_files(&zip_archive); + for (i = 0; i < n; ++i) { + if (!mz_zip_reader_file_stat(&zip_archive, i, &info)) { + // Cannot get information about zip archive; + goto out; + } +#if defined(_MSC_VER) + strncpy_s(&path[dirlen], MAX_PATH - dirlen, info.m_filename, + MAX_PATH - dirlen); +#else + strncpy(&path[dirlen], info.m_filename, MAX_PATH - dirlen); +#endif + if (mkpath(path) < 0) { + // Cannot make a path + goto out; } - // Get and print information about each file in the archive. - n = mz_zip_reader_get_num_files(&zip_archive); - for (i = 0; i < n; ++i) { - if (!mz_zip_reader_file_stat(&zip_archive, i, &info)) { - // Cannot get information about zip archive; - goto out; - } - strncpy(&path[dirlen], info.m_filename, MAX_PATH - dirlen); - if (mkpath(path) < 0) { - // Cannot make a path - goto out; + if ((((info.m_version_made_by >> 8) == 3) || ((info.m_version_made_by >> 8) == 19)) // if zip is produced on Unix or macOS (3 and 19 from section 4.4.2.2 of zip standard) + && info.m_external_attr & (0x20 << 24)) { // and has sym link attribute (0x80 is file, 0x40 is directory) +#if defined(_WIN32) || defined(__WIN32__) || defined(_MSC_VER) || \ + defined(__MINGW32__) +#else + if (info.m_uncomp_size > MAX_PATH || !mz_zip_reader_extract_to_mem_no_alloc(&zip_archive, i, symlink_to, MAX_PATH, 0, NULL, 0)) { + goto out; + } + symlink_to[info.m_uncomp_size] = '\0'; + if (symlink(symlink_to, path) != 0) { + goto out; + } +#endif + } else { + if (!mz_zip_reader_is_file_a_directory(&zip_archive, i)) { + if (!mz_zip_reader_extract_to_file(&zip_archive, i, path, 0)) { + // Cannot extract zip archive to file + goto out; } + } - if (!mz_zip_reader_is_file_a_directory(&zip_archive, i)) { - if (!mz_zip_reader_extract_to_file(&zip_archive, i, path, 0)) { - // Cannot extract zip archive to file - goto out; - } - } - - if (on_extract) { - if (on_extract(path, arg) < 0) { - goto out; - } +#if defined(_MSC_VER) +#else + xattr = (info.m_external_attr >> 16) & 0xFFFF; + if (xattr > 0) { + if (chmod(path, (mode_t)xattr) < 0) { + goto out; } + } +#endif } - status = 0; + + if (on_extract) { + if (on_extract(path, arg) < 0) { + goto out; + } + } + } + status = 0; out: - // Close the archive, freeing any resources it was using - if (!mz_zip_reader_end(&zip_archive)) { - // Cannot end zip reader - status = -1; - } + // Close the archive, freeing any resources it was using + if (!mz_zip_reader_end(&zip_archive)) { + // Cannot end zip reader + status = -1; + } - return status; + return status; } diff --git a/third_party/libassimp/contrib/zip/src/zip.h b/third_party/libassimp/contrib/zip/src/zip.h index 1611b54176..5f39df50ad 100644 --- a/third_party/libassimp/contrib/zip/src/zip.h +++ b/third_party/libassimp/contrib/zip/src/zip.h @@ -13,11 +13,24 @@ #define ZIP_H #include +#include #ifdef __cplusplus extern "C" { #endif +#if !defined(_SSIZE_T_DEFINED) && !defined(_SSIZE_T_DEFINED_) && \ + !defined(_SSIZE_T) && !defined(_SSIZE_T_) && !defined(__ssize_t_defined) +#define _SSIZE_T +// 64-bit Windows is the only mainstream platform +// where sizeof(long) != sizeof(void*) +#ifdef _WIN64 +typedef long long ssize_t; /* byte count or error */ +#else +typedef long ssize_t; /* byte count or error */ +#endif +#endif + #ifndef MAX_PATH #define MAX_PATH 32767 /* # chars in a path name including NULL */ #endif @@ -47,7 +60,7 @@ struct zip_t; extern struct zip_t *zip_open(const char *zipname, int level, char mode); /* - Closes zip archive, releases resources - always finalize. + Closes the zip archive, releases resources - always finalize. Args: zip: zip archive handler. @@ -55,7 +68,10 @@ extern struct zip_t *zip_open(const char *zipname, int level, char mode); extern void zip_close(struct zip_t *zip); /* - Opens a new entry for writing in a zip archive. + Opens an entry by name in the zip archive. + For zip archive opened in 'w' or 'a' mode the function will append + a new entry. In readonly mode the function tries to locate the entry + in global dictionary. Args: zip: zip archive handler. @@ -66,6 +82,19 @@ extern void zip_close(struct zip_t *zip); */ extern int zip_entry_open(struct zip_t *zip, const char *entryname); +/* + Opens a new entry by index in the zip archive. + This function is only valid if zip archive was opened in 'r' (readonly) mode. + + Args: + zip: zip archive handler. + index: index in local dictionary. + + Returns: + The return code - 0 on success, negative number (< 0) on error. +*/ +extern int zip_entry_openbyindex(struct zip_t *zip, int index); + /* Closes a zip entry, flushes buffer and releases resources. @@ -77,6 +106,67 @@ extern int zip_entry_open(struct zip_t *zip, const char *entryname); */ extern int zip_entry_close(struct zip_t *zip); +/* + Returns a local name of the current zip entry. + The main difference between user's entry name and local entry name + is optional relative path. + Following .ZIP File Format Specification - the path stored MUST not contain + a drive or device letter, or a leading slash. + All slashes MUST be forward slashes '/' as opposed to backwards slashes '\' + for compatibility with Amiga and UNIX file systems etc. + + Args: + zip: zip archive handler. + + Returns: + The pointer to the current zip entry name, or NULL on error. +*/ +extern const char *zip_entry_name(struct zip_t *zip); + +/* + Returns an index of the current zip entry. + + Args: + zip: zip archive handler. + + Returns: + The index on success, negative number (< 0) on error. +*/ +extern int zip_entry_index(struct zip_t *zip); + +/* + Determines if the current zip entry is a directory entry. + + Args: + zip: zip archive handler. + + Returns: + The return code - 1 (true), 0 (false), negative number (< 0) on error. +*/ +extern int zip_entry_isdir(struct zip_t *zip); + +/* + Returns an uncompressed size of the current zip entry. + + Args: + zip: zip archive handler. + + Returns: + The uncompressed size in bytes. +*/ +extern unsigned long long zip_entry_size(struct zip_t *zip); + +/* + Returns CRC-32 checksum of the current zip entry. + + Args: + zip: zip archive handler. + + Returns: + The CRC-32 checksum. +*/ +extern unsigned int zip_entry_crc32(struct zip_t *zip); + /* Compresses an input buffer for the current zip entry. @@ -116,9 +206,31 @@ extern int zip_entry_fwrite(struct zip_t *zip, const char *filename); - for large entries, please take a look at zip_entry_extract function. Returns: - The return code - 0 on success, negative number (< 0) on error. + The return code - the number of bytes actually read on success. + Otherwise a -1 on error. */ -extern int zip_entry_read(struct zip_t *zip, void **buf, size_t *bufsize); +extern ssize_t zip_entry_read(struct zip_t *zip, void **buf, size_t *bufsize); + +/* + Extracts the current zip entry into a memory buffer using no memory + allocation. + + Args: + zip: zip archive handler. + buf: preallocated output buffer. + bufsize: output buffer size (in bytes). + + Note: + - ensure supplied output buffer is large enough. + - zip_entry_size function (returns uncompressed size for the current entry) + can be handy to estimate how big buffer is needed. + - for large entries, please take a look at zip_entry_extract function. + + Returns: + The return code - the number of bytes actually read on success. + Otherwise a -1 on error (e.g. bufsize is not large enough). +*/ +extern ssize_t zip_entry_noallocread(struct zip_t *zip, void *buf, size_t bufsize); /* Extracts the current zip entry into output file. @@ -133,9 +245,9 @@ extern int zip_entry_read(struct zip_t *zip, void **buf, size_t *bufsize); extern int zip_entry_fread(struct zip_t *zip, const char *filename); /* - Extract the current zip entry using a callback function (on_extract). + Extracts the current zip entry using a callback function (on_extract). - Args: + Args: zip: zip archive handler. on_extract: callback function. arg: opaque pointer (optional argument, @@ -144,12 +256,23 @@ extern int zip_entry_fread(struct zip_t *zip, const char *filename); Returns: The return code - 0 on success, negative number (< 0) on error. */ -extern int zip_entry_extract(struct zip_t *zip, - size_t (*on_extract)(void *arg, - unsigned long long offset, - const void *data, - size_t size), - void *arg); +extern int +zip_entry_extract(struct zip_t *zip, + size_t (*on_extract)(void *arg, unsigned long long offset, + const void *data, size_t size), + void *arg); + +/* + Returns the number of all entries (files and directories) in the zip archive. + + Args: + zip: zip archive handler. + + Returns: + The return code - the number of entries on success, + negative number (< 0) on error. +*/ +extern int zip_total_entries(struct zip_t *zip); /* Creates a new archive and puts files into a single zip archive. diff --git a/third_party/libassimp/contrib/zip/test/CMakeLists.txt b/third_party/libassimp/contrib/zip/test/CMakeLists.txt index 7734dcbe75..9b2a8db106 100644 --- a/third_party/libassimp/contrib/zip/test/CMakeLists.txt +++ b/third_party/libassimp/contrib/zip/test/CMakeLists.txt @@ -1,7 +1,19 @@ cmake_minimum_required(VERSION 2.8) +if ("${CMAKE_C_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_C_COMPILER_ID}" STREQUAL "Clang" OR "${CMAKE_C_COMPILER_ID}" STREQUAL "AppleClang") + if(ENABLE_COVERAGE) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g ") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ftest-coverage") + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} --coverage") + endif() +endif () + # test include_directories(../src) add_executable(test.exe test.c ../src/zip.c) +add_executable(test_miniz.exe test_miniz.c) add_test(NAME test COMMAND test.exe) +add_test(NAME test_miniz COMMAND test_miniz.exe) diff --git a/third_party/libassimp/contrib/zip/test/test.c b/third_party/libassimp/contrib/zip/test/test.c index 0b9c9f7b62..454430533a 100644 --- a/third_party/libassimp/contrib/zip/test/test.c +++ b/third_party/libassimp/contrib/zip/test/test.c @@ -4,102 +4,456 @@ #include #include #include +#include -#define ZIPNAME "test.zip" +#if defined(_MSC_VER) || defined(__MINGW64__) || defined(__MINGW32__) +#define MZ_FILE_STAT_STRUCT _stat +#define MZ_FILE_STAT _stat +#else +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#endif + +#define ZIPNAME "test.zip\0" #define TESTDATA1 "Some test data 1...\0" +#define CRC32DATA1 2220805626 #define TESTDATA2 "Some test data 2...\0" +#define CRC32DATA2 2532008468 + +#define RFILE "4.txt\0" +#define RMODE 0100444 + +#define WFILE "6.txt\0" +#define WMODE 0100666 + +#define XFILE "7.txt\0" +#define XMODE 0100777 + +#define UNUSED(x) (void)x + +static int total_entries = 0; static void test_write(void) { - struct zip_t *zip = zip_open(ZIPNAME, ZIP_DEFAULT_COMPRESSION_LEVEL, 'w'); - assert(zip != NULL); + struct zip_t *zip = zip_open(ZIPNAME, ZIP_DEFAULT_COMPRESSION_LEVEL, 'w'); + assert(zip != NULL); - assert(0 == zip_entry_open(zip, "test/test-1.txt")); - assert(0 == zip_entry_write(zip, TESTDATA1, strlen(TESTDATA1))); - assert(0 == zip_entry_close(zip)); + assert(0 == zip_entry_open(zip, "test/test-1.txt")); + assert(0 == zip_entry_write(zip, TESTDATA1, strlen(TESTDATA1))); + assert(0 == strcmp(zip_entry_name(zip), "test/test-1.txt")); + assert(total_entries == zip_entry_index(zip)); + assert(strlen(TESTDATA1) == zip_entry_size(zip)); + assert(CRC32DATA1 == zip_entry_crc32(zip)); + ++total_entries; + assert(0 == zip_entry_close(zip)); - zip_close(zip); + zip_close(zip); } static void test_append(void) { - struct zip_t *zip = zip_open(ZIPNAME, ZIP_DEFAULT_COMPRESSION_LEVEL, 'a'); - assert(zip != NULL); + struct zip_t *zip = zip_open(ZIPNAME, ZIP_DEFAULT_COMPRESSION_LEVEL, 'a'); + assert(zip != NULL); - assert(0 == zip_entry_open(zip, "test\\test-2.txt")); - assert(0 == zip_entry_write(zip, TESTDATA2, strlen(TESTDATA2))); - assert(0 == zip_entry_close(zip)); + assert(0 == zip_entry_open(zip, "test\\test-2.txt")); + assert(0 == strcmp(zip_entry_name(zip), "test/test-2.txt")); + assert(total_entries == zip_entry_index(zip)); + assert(0 == zip_entry_write(zip, TESTDATA2, strlen(TESTDATA2))); + assert(strlen(TESTDATA2) == zip_entry_size(zip)); + assert(CRC32DATA2 == zip_entry_crc32(zip)); - zip_close(zip); + ++total_entries; + assert(0 == zip_entry_close(zip)); + + assert(0 == zip_entry_open(zip, "test\\empty/")); + assert(0 == strcmp(zip_entry_name(zip), "test/empty/")); + assert(0 == zip_entry_size(zip)); + assert(0 == zip_entry_crc32(zip)); + + assert(total_entries == zip_entry_index(zip)); + ++total_entries; + assert(0 == zip_entry_close(zip)); + + assert(0 == zip_entry_open(zip, "empty/")); + assert(0 == strcmp(zip_entry_name(zip), "empty/")); + assert(0 == zip_entry_size(zip)); + assert(0 == zip_entry_crc32(zip)); + + assert(total_entries == zip_entry_index(zip)); + ++total_entries; + assert(0 == zip_entry_close(zip)); + + zip_close(zip); } static void test_read(void) { - char *buf = NULL; - size_t bufsize; - struct zip_t *zip = zip_open(ZIPNAME, 0, 'r'); - assert(zip != NULL); + char *buf = NULL; + ssize_t bufsize; + size_t buftmp; + struct zip_t *zip = zip_open(ZIPNAME, 0, 'r'); + assert(zip != NULL); - assert(0 == zip_entry_open(zip, "test\\test-1.txt")); - assert(0 == zip_entry_read(zip, (void **)&buf, &bufsize)); - assert(bufsize == strlen(TESTDATA1)); - assert(0 == strncmp(buf, TESTDATA1, bufsize)); - assert(0 == zip_entry_close(zip)); - free(buf); - buf = NULL; - bufsize = 0; + assert(0 == zip_entry_open(zip, "test\\test-1.txt")); + assert(strlen(TESTDATA1) == zip_entry_size(zip)); + assert(CRC32DATA1 == zip_entry_crc32(zip)); - assert(0 == zip_entry_open(zip, "test/test-2.txt")); - assert(0 == zip_entry_read(zip, (void **)&buf, &bufsize)); - assert(bufsize == strlen(TESTDATA2)); - assert(0 == strncmp(buf, TESTDATA2, bufsize)); - assert(0 == zip_entry_close(zip)); - free(buf); - buf = NULL; - bufsize = 0; + bufsize = zip_entry_read(zip, (void **)&buf, &buftmp); + assert(bufsize == strlen(TESTDATA1)); + assert((size_t)bufsize == buftmp); + assert(0 == strncmp(buf, TESTDATA1, bufsize)); + assert(0 == zip_entry_close(zip)); + free(buf); + buf = NULL; + + assert(0 == zip_entry_open(zip, "test/test-2.txt")); + assert(strlen(TESTDATA2) == zip_entry_size(zip)); + assert(CRC32DATA2 == zip_entry_crc32(zip)); - zip_close(zip); + bufsize = zip_entry_read(zip, (void **)&buf, NULL); + assert((size_t)bufsize == strlen(TESTDATA2)); + assert(0 == strncmp(buf, TESTDATA2, (size_t)bufsize)); + assert(0 == zip_entry_close(zip)); + free(buf); + buf = NULL; + bufsize = 0; + + assert(0 == zip_entry_open(zip, "test\\empty/")); + assert(0 == strcmp(zip_entry_name(zip), "test/empty/")); + assert(0 == zip_entry_size(zip)); + assert(0 == zip_entry_crc32(zip)); + assert(0 == zip_entry_close(zip)); + + buftmp = strlen(TESTDATA2); + buf = calloc(buftmp, sizeof(char)); + assert(0 == zip_entry_open(zip, "test/test-2.txt")); + + bufsize = zip_entry_noallocread(zip, (void *)buf, buftmp); + assert(buftmp == (size_t)bufsize); + assert(0 == strncmp(buf, TESTDATA2, buftmp)); + assert(0 == zip_entry_close(zip)); + free(buf); + buf = NULL; + + buftmp = strlen(TESTDATA1); + buf = calloc(buftmp, sizeof(char)); + assert(0 == zip_entry_open(zip, "test/test-1.txt")); + + bufsize = zip_entry_noallocread(zip, (void *)buf, buftmp); + assert(buftmp == (size_t)bufsize); + assert(0 == strncmp(buf, TESTDATA1, buftmp)); + assert(0 == zip_entry_close(zip)); + free(buf); + buf = NULL; + bufsize = 0; + + zip_close(zip); } struct buffer_t { - char *data; - size_t size; + char *data; + size_t size; }; static size_t on_extract(void *arg, unsigned long long offset, const void *data, size_t size) { - struct buffer_t *buf = (struct buffer_t *)arg; - buf->data = realloc(buf->data, buf->size + size + 1); - assert(NULL != buf->data); + UNUSED(offset); - memcpy(&(buf->data[buf->size]), data, size); - buf->size += size; - buf->data[buf->size] = 0; + struct buffer_t *buf = (struct buffer_t *)arg; + buf->data = realloc(buf->data, buf->size + size + 1); + assert(NULL != buf->data); - return size; + memcpy(&(buf->data[buf->size]), data, size); + buf->size += size; + buf->data[buf->size] = 0; + + return size; } static void test_extract(void) { - struct buffer_t buf = {0}; + struct buffer_t buf; - struct zip_t *zip = zip_open(ZIPNAME, 0, 'r'); - assert(zip != NULL); + struct zip_t *zip = zip_open(ZIPNAME, 0, 'r'); + assert(zip != NULL); + memset((void *)&buf, 0, sizeof(struct buffer_t)); - assert(0 == zip_entry_open(zip, "test/test-1.txt")); - assert(0 == zip_entry_extract(zip, on_extract, &buf)); + assert(0 == zip_entry_open(zip, "test/test-1.txt")); + assert(0 == zip_entry_extract(zip, on_extract, &buf)); - assert(buf.size == strlen(TESTDATA1)); - assert(0 == strncmp(buf.data, TESTDATA1, buf.size)); + assert(buf.size == strlen(TESTDATA1)); + assert(0 == strncmp(buf.data, TESTDATA1, buf.size)); + assert(0 == zip_entry_close(zip)); + free(buf.data); + buf.data = NULL; + buf.size = 0; + + zip_close(zip); +} + +static void test_total_entries(void) { + struct zip_t *zip = zip_open(ZIPNAME, 0, 'r'); + assert(zip != NULL); + + int n = zip_total_entries(zip); + zip_close(zip); + + assert(n == total_entries); +} + +static void test_entry_name(void) { + struct zip_t *zip = zip_open(ZIPNAME, 0, 'r'); + assert(zip != NULL); + + assert(zip_entry_name(zip) == NULL); + + assert(0 == zip_entry_open(zip, "test\\test-1.txt")); + assert(NULL != zip_entry_name(zip)); + assert(0 == strcmp(zip_entry_name(zip), "test/test-1.txt")); + assert(strlen(TESTDATA1) == zip_entry_size(zip)); + assert(CRC32DATA1 == zip_entry_crc32(zip)); + assert(0 == zip_entry_index(zip)); + + assert(0 == zip_entry_close(zip)); + + assert(0 == zip_entry_open(zip, "test/test-2.txt")); + assert(NULL != zip_entry_name(zip)); + assert(0 == strcmp(zip_entry_name(zip), "test/test-2.txt")); + assert(strlen(TESTDATA2) == zip_entry_size(zip)); + assert(CRC32DATA2 == zip_entry_crc32(zip)); + assert(1 == zip_entry_index(zip)); + + assert(0 == zip_entry_close(zip)); + + zip_close(zip); +} + +static void test_entry_index(void) { + struct zip_t *zip = zip_open(ZIPNAME, 0, 'r'); + assert(zip != NULL); + + assert(0 == zip_entry_open(zip, "test\\test-1.txt")); + assert(0 == zip_entry_index(zip)); + assert(0 == strcmp(zip_entry_name(zip), "test/test-1.txt")); + assert(strlen(TESTDATA1) == zip_entry_size(zip)); + assert(CRC32DATA1 == zip_entry_crc32(zip)); + assert(0 == zip_entry_close(zip)); + + assert(0 == zip_entry_open(zip, "test/test-2.txt")); + assert(1 == zip_entry_index(zip)); + assert(0 == strcmp(zip_entry_name(zip), "test/test-2.txt")); + assert(strlen(TESTDATA2) == zip_entry_size(zip)); + assert(CRC32DATA2 == zip_entry_crc32(zip)); + assert(0 == zip_entry_close(zip)); + + zip_close(zip); +} + +static void test_entry_openbyindex(void) { + struct zip_t *zip = zip_open(ZIPNAME, 0, 'r'); + assert(zip != NULL); + + assert(0 == zip_entry_openbyindex(zip, 1)); + assert(1 == zip_entry_index(zip)); + assert(strlen(TESTDATA2) == zip_entry_size(zip)); + assert(CRC32DATA2 == zip_entry_crc32(zip)); + assert(0 == strcmp(zip_entry_name(zip), "test/test-2.txt")); + assert(0 == zip_entry_close(zip)); + + assert(0 == zip_entry_openbyindex(zip, 0)); + assert(0 == zip_entry_index(zip)); + assert(strlen(TESTDATA1) == zip_entry_size(zip)); + assert(CRC32DATA1 == zip_entry_crc32(zip)); + assert(0 == strcmp(zip_entry_name(zip), "test/test-1.txt")); + assert(0 == zip_entry_close(zip)); + + zip_close(zip); +} + +static void test_list_entries(void) { + struct zip_t *zip = zip_open(ZIPNAME, 0, 'r'); + assert(zip != NULL); + + int i = 0, n = zip_total_entries(zip); + for (; i < n; ++i) { + assert(0 == zip_entry_openbyindex(zip, i)); + fprintf(stdout, "[%d]: %s", i, zip_entry_name(zip)); + if (zip_entry_isdir(zip)) { + fprintf(stdout, " (DIR)"); + } + fprintf(stdout, "\n"); assert(0 == zip_entry_close(zip)); - free(buf.data); - buf.data = NULL; - buf.size = 0; + } - zip_close(zip); + zip_close(zip); +} + +static void test_fwrite(void) { + const char *filename = WFILE; + FILE *stream = NULL; + struct zip_t *zip = NULL; +#if defined(_MSC_VER) + if (0 != fopen_s(&stream, filename, "w+")) +#else + if (!(stream = fopen(filename, "w+"))) +#endif + { + // Cannot open filename + fprintf(stdout, "Cannot open filename\n"); + assert(0 == -1); + } + fwrite(TESTDATA1, sizeof(char), strlen(TESTDATA1), stream); + assert(0 == fclose(stream)); + + zip = zip_open(ZIPNAME, 9, 'w'); + assert(zip != NULL); + assert(0 == zip_entry_open(zip, WFILE)); + assert(0 == zip_entry_fwrite(zip, WFILE)); + assert(0 == zip_entry_close(zip)); + + zip_close(zip); + remove(WFILE); + remove(ZIPNAME); +} + +static void test_exe_permissions(void) { +#if defined(_WIN32) || defined(__WIN32__) +#else + struct MZ_FILE_STAT_STRUCT file_stats; + const char *filenames[] = {XFILE}; + FILE *f = fopen(XFILE, "w"); + fclose(f); + chmod(XFILE, XMODE); + + remove(ZIPNAME); + + assert(0 == zip_create(ZIPNAME, filenames, 1)); + + remove(XFILE); + + assert(0 == zip_extract(ZIPNAME, ".", NULL, NULL)); + + assert(0 == MZ_FILE_STAT(XFILE, &file_stats)); + assert(XMODE == file_stats.st_mode); + + remove(XFILE); + remove(ZIPNAME); +#endif +} + +static void test_read_permissions(void) { +#if defined(_MSC_VER) +#else + + struct MZ_FILE_STAT_STRUCT file_stats; + const char *filenames[] = {RFILE}; + FILE *f = fopen(RFILE, "w"); + fclose(f); + chmod(RFILE, RMODE); + + remove(ZIPNAME); + + assert(0 == zip_create(ZIPNAME, filenames, 1)); + + // chmod from 444 to 666 to be able delete the file on windows + chmod(RFILE, WMODE); + remove(RFILE); + + assert(0 == zip_extract(ZIPNAME, ".", NULL, NULL)); + + assert(0 == MZ_FILE_STAT(RFILE, &file_stats)); + assert(RMODE == file_stats.st_mode); + + chmod(RFILE, WMODE); + remove(RFILE); + remove(ZIPNAME); +#endif +} + +static void test_write_permissions(void) { +#if defined(_MSC_VER) +#else + + struct MZ_FILE_STAT_STRUCT file_stats; + const char *filenames[] = {WFILE}; + FILE *f = fopen(WFILE, "w"); + fclose(f); + chmod(WFILE, WMODE); + + remove(ZIPNAME); + + assert(0 == zip_create(ZIPNAME, filenames, 1)); + + remove(WFILE); + + assert(0 == zip_extract(ZIPNAME, ".", NULL, NULL)); + + assert(0 == MZ_FILE_STAT(WFILE, &file_stats)); + assert(WMODE == file_stats.st_mode); + + remove(WFILE); + remove(ZIPNAME); +#endif +} + +static void test_mtime(void) { + struct MZ_FILE_STAT_STRUCT file_stat1, file_stat2; + + const char *filename = WFILE; + FILE *stream = NULL; + struct zip_t *zip = NULL; +#if defined(_MSC_VER) + if (0 != fopen_s(&stream, filename, "w+")) +#else + if (!(stream = fopen(filename, "w+"))) +#endif + { + // Cannot open filename + fprintf(stdout, "Cannot open filename\n"); + assert(0 == -1); + } + fwrite(TESTDATA1, sizeof(char), strlen(TESTDATA1), stream); + assert(0 == fclose(stream)); + + memset(&file_stat1, 0, sizeof(file_stat1)); + memset(&file_stat2, 0, sizeof(file_stat2)); + zip = zip_open(ZIPNAME, ZIP_DEFAULT_COMPRESSION_LEVEL, 'w'); + assert(zip != NULL); + assert(0 == zip_entry_open(zip, filename)); + assert(0 == zip_entry_fwrite(zip, filename)); + assert(0 == zip_entry_close(zip)); + zip_close(zip); + + assert(0 == MZ_FILE_STAT(filename, &file_stat1)); + + remove(filename); + assert(0 == zip_extract(ZIPNAME, ".", NULL, NULL)); + assert(0 == MZ_FILE_STAT(filename, &file_stat2)); + fprintf(stdout, "file_stat1.st_mtime: %lu\n", file_stat1.st_mtime); + fprintf(stdout, "file_stat2.st_mtime: %lu\n", file_stat2.st_mtime); + assert(labs(file_stat1.st_mtime - file_stat2.st_mtime) <= 1); + + remove(filename); + remove(ZIPNAME); } int main(int argc, char *argv[]) { - test_write(); - test_append(); - test_read(); - test_extract(); + UNUSED(argc); + UNUSED(argv); - return remove(ZIPNAME); + remove(ZIPNAME); + + test_write(); + test_append(); + test_read(); + test_extract(); + test_total_entries(); + test_entry_name(); + test_entry_index(); + test_entry_openbyindex(); + test_list_entries(); + test_fwrite(); + test_read_permissions(); + test_write_permissions(); + test_exe_permissions(); + test_mtime(); + + remove(ZIPNAME); + return 0; } diff --git a/third_party/libassimp/contrib/zip/test/test_miniz.c b/third_party/libassimp/contrib/zip/test/test_miniz.c new file mode 100644 index 0000000000..ebc0564dc3 --- /dev/null +++ b/third_party/libassimp/contrib/zip/test/test_miniz.c @@ -0,0 +1,104 @@ +// Demonstrates miniz.c's compress() and uncompress() functions +// (same as zlib's). Public domain, May 15 2011, Rich Geldreich, +// richgel99@gmail.com. See "unlicense" statement at the end of tinfl.c. + +#include +#include + +typedef unsigned char uint8; +typedef unsigned short uint16; +typedef unsigned int uint; + +// The string to compress. +static const char *s_pStr = + "Good morning Dr. Chandra. This is Hal. I am ready for my first lesson." + "Good morning Dr. Chandra. This is Hal. I am ready for my first lesson." + "Good morning Dr. Chandra. This is Hal. I am ready for my first lesson." + "Good morning Dr. Chandra. This is Hal. I am ready for my first lesson." + "Good morning Dr. Chandra. This is Hal. I am ready for my first lesson." + "Good morning Dr. Chandra. This is Hal. I am ready for my first lesson." + "Good morning Dr. Chandra. This is Hal. I am ready for my first lesson."; + +int main(int argc, char *argv[]) { + uint step = 0; + int cmp_status; + uLong src_len = (uLong)strlen(s_pStr); + uLong cmp_len = compressBound(src_len); + uLong uncomp_len = src_len; + uint8 *pCmp, *pUncomp; + uint total_succeeded = 0; + (void)argc, (void)argv; + + printf("miniz.c version: %s\n", MZ_VERSION); + + do { + // Allocate buffers to hold compressed and uncompressed data. + pCmp = (mz_uint8 *)malloc((size_t)cmp_len); + pUncomp = (mz_uint8 *)malloc((size_t)src_len); + if ((!pCmp) || (!pUncomp)) { + printf("Out of memory!\n"); + return EXIT_FAILURE; + } + + // Compress the string. + cmp_status = + compress(pCmp, &cmp_len, (const unsigned char *)s_pStr, src_len); + if (cmp_status != Z_OK) { + printf("compress() failed!\n"); + free(pCmp); + free(pUncomp); + return EXIT_FAILURE; + } + + printf("Compressed from %u to %u bytes\n", (mz_uint32)src_len, + (mz_uint32)cmp_len); + + if (step) { + // Purposely corrupt the compressed data if fuzzy testing (this is a + // very crude fuzzy test). + uint n = 1 + (rand() % 3); + while (n--) { + uint i = rand() % cmp_len; + pCmp[i] ^= (rand() & 0xFF); + } + } + + // Decompress. + cmp_status = uncompress(pUncomp, &uncomp_len, pCmp, cmp_len); + total_succeeded += (cmp_status == Z_OK); + + if (step) { + printf("Simple fuzzy test: step %u total_succeeded: %u\n", step, + total_succeeded); + } else { + if (cmp_status != Z_OK) { + printf("uncompress failed!\n"); + free(pCmp); + free(pUncomp); + return EXIT_FAILURE; + } + + printf("Decompressed from %u to %u bytes\n", (mz_uint32)cmp_len, + (mz_uint32)uncomp_len); + + // Ensure uncompress() returned the expected data. + if ((uncomp_len != src_len) || + (memcmp(pUncomp, s_pStr, (size_t)src_len))) { + printf("Decompression failed!\n"); + free(pCmp); + free(pUncomp); + return EXIT_FAILURE; + } + } + + free(pCmp); + free(pUncomp); + + step++; + + // Keep on fuzzy testing if there's a non-empty command line. + } while (argc >= 2); + + printf("Success.\n"); + return EXIT_SUCCESS; +} diff --git a/third_party/libassimp/contrib/zlib/CMakeLists.txt b/third_party/libassimp/contrib/zlib/CMakeLists.txt index 5f1368adb9..9d1fcc943e 100644 --- a/third_party/libassimp/contrib/zlib/CMakeLists.txt +++ b/third_party/libassimp/contrib/zlib/CMakeLists.txt @@ -5,12 +5,17 @@ set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS ON) # See http://www.cmake.org/cmake/help/v3.0/policy/CMP0048.html cmake_policy(PUSH) if(CMAKE_MAJOR_VERSION GREATER 2) - cmake_policy(SET CMP0048 OLD) + cmake_policy(SET CMP0048 NEW) endif() project(zlib C) +SET (ZLIB_VERSION_MAJOR 1) +SET (ZLIB_VERSION_MINOR 2) +SET (ZLIB_VERSION_PATCH 11) +SET (ZLIB_VERSION ${ZLIB_VERSION_MAJOR}.${ZLIB_VERSION_MINOR}.${ZLIB_VERSION_PATCH}) +SET (ZLIB_SOVERSION 1) +SET (PROJECT_VERSION "${ZLIB_VERSION}") cmake_policy(POP) -set(VERSION "1.2.11.1") option(ASM686 "Enable building i686 assembly implementation") option(AMD64 "Enable building amd64 assembly implementation") diff --git a/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/ChecksumImpl.cs b/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/ChecksumImpl.cs index b110dae6a1..cd1ef44eb1 100644 --- a/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/ChecksumImpl.cs +++ b/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/ChecksumImpl.cs @@ -1,5 +1,5 @@ // -// Copyright Henrik Ravn 2004 +// © Copyright Henrik Ravn 2004 // // Use, modification and distribution are subject to the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -199,4 +199,4 @@ namespace DotZLib } #endregion -} \ No newline at end of file +} diff --git a/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/CircularBuffer.cs b/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/CircularBuffer.cs index 9c8d601954..e7a88b9f4d 100644 --- a/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/CircularBuffer.cs +++ b/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/CircularBuffer.cs @@ -1,5 +1,5 @@ // -// Copyright Henrik Ravn 2004 +// © Copyright Henrik Ravn 2004 // // Use, modification and distribution are subject to the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) diff --git a/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/CodecBase.cs b/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/CodecBase.cs index b0eb78a022..6ef6d8fab9 100644 --- a/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/CodecBase.cs +++ b/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/CodecBase.cs @@ -1,5 +1,5 @@ // -// Copyright Henrik Ravn 2004 +// © Copyright Henrik Ravn 2004 // // Use, modification and distribution are subject to the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) diff --git a/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/Deflater.cs b/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/Deflater.cs index 9039f41f66..778a6794dd 100644 --- a/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/Deflater.cs +++ b/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/Deflater.cs @@ -1,5 +1,5 @@ // -// Copyright Henrik Ravn 2004 +// © Copyright Henrik Ravn 2004 // // Use, modification and distribution are subject to the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) diff --git a/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/DotZLib.cs b/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/DotZLib.cs index 90c7c3b380..a48ed4974d 100644 --- a/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/DotZLib.cs +++ b/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/DotZLib.cs @@ -1,5 +1,5 @@ // -// Copyright Henrik Ravn 2004 +// © Copyright Henrik Ravn 2004 // // Use, modification and distribution are subject to the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) diff --git a/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/GZipStream.cs b/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/GZipStream.cs index f0eada1d24..07b2f7a9b5 100644 --- a/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/GZipStream.cs +++ b/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/GZipStream.cs @@ -1,5 +1,5 @@ // -// Copyright Henrik Ravn 2004 +// © Copyright Henrik Ravn 2004 // // Use, modification and distribution are subject to the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) diff --git a/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/Inflater.cs b/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/Inflater.cs index d295f26804..8e900ae204 100644 --- a/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/Inflater.cs +++ b/third_party/libassimp/contrib/zlib/contrib/dotzlib/DotZLib/Inflater.cs @@ -1,5 +1,5 @@ // -// Copyright Henrik Ravn 2004 +// © Copyright Henrik Ravn 2004 // // Use, modification and distribution are subject to the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) diff --git a/third_party/libassimp/doc/dox.h b/third_party/libassimp/doc/dox.h index d63c8a806a..910e77eaea 100644 --- a/third_party/libassimp/doc/dox.h +++ b/third_party/libassimp/doc/dox.h @@ -1173,6 +1173,18 @@ float4 PimpMyPixel (float4 prev) @endcode +@section shdacc How to access shader-code from a texture (AI_MATKEY_GLOBAL_SHADERLANG and AI_MATKEY_SHADER_VERTEX, ...) + +You can get assigned shader sources by using the following material keys: + +
  • AI_MATKEY_GLOBAL_SHADERLANG
  • To get the used shader language. +
  • AI_MATKEY_SHADER_VERTEX
  • Assigned vertex shader code stored as a string. +
  • AI_MATKEY_SHADER_FRAGMENT
  • Assigned fragment shader code stored as a string. +
  • AI_MATKEY_SHADER_GEO
  • Assigned geometry shader code stored as a string. +
  • AI_MATKEY_SHADER_TESSELATION
  • Assigned tesselation shader code stored as a string. +
  • AI_MATKEY_SHADER_PRIMITIVE
  • Assigned primitive shader code stored as a string. +
  • AI_MATKEY_SHADER_COMPUTE
  • Assigned compute shader code stored as a string. + */ diff --git a/third_party/libassimp/include/assimp/BaseImporter.h b/third_party/libassimp/include/assimp/BaseImporter.h index b218d06ffc..55f7fe3754 100644 --- a/third_party/libassimp/include/assimp/BaseImporter.h +++ b/third_party/libassimp/include/assimp/BaseImporter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -48,8 +48,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include +#include #include #include +#include struct aiScene; struct aiImporterDesc; @@ -80,6 +82,10 @@ class IOStream; class ASSIMP_API BaseImporter { friend class Importer; +private: + /* Pushes state into importer for the importer scale */ + virtual void UpdateImporterScale( Importer* pImp ); + public: /** Constructor to be privately used by #Importer */ @@ -132,7 +138,7 @@ public: * a suitable response to the caller. */ aiScene* ReadFile( - const Importer* pImp, + Importer* pImp, const std::string& pFile, IOSystem* pIOHandler ); @@ -161,14 +167,65 @@ public: * some loader features. Importers must provide this information. */ virtual const aiImporterDesc* GetInfo() const = 0; + /** + * Will be called only by scale process when scaling is requested. + */ + virtual void SetFileScale(double scale) + { + fileScale = scale; + } + + virtual double GetFileScale() const + { + return fileScale; + } + + enum ImporterUnits { + M, + MM, + CM, + INCHES, + FEET + }; + + /** + * Assimp Importer + * unit conversions available + * if you need another measurment unit add it below. + * it's currently defined in assimp that we prefer meters. + * */ + std::map importerUnits = { + {ImporterUnits::M, 1}, + {ImporterUnits::CM, 0.01}, + {ImporterUnits::MM, 0.001}, + {ImporterUnits::INCHES, 0.0254}, + {ImporterUnits::FEET, 0.3048} + }; + + virtual void SetApplicationUnits( const ImporterUnits& unit ) + { + importerScale = importerUnits[unit]; + applicationUnits = unit; + } + + virtual const ImporterUnits& GetApplicationUnits() + { + return applicationUnits; + } + // ------------------------------------------------------------------- /** Called by #Importer::GetExtensionList for each loaded importer. * Take the extension list contained in the structure returned by * #GetInfo and insert all file extensions into the given set. * @param extension set to collect file extensions in*/ void GetExtensionList(std::set& extensions); + +protected: + ImporterUnits applicationUnits = ImporterUnits::M; + double importerScale = 1.0; + double fileScale = 1.0; + -protected: // ------------------------------------------------------------------- /** Imports the given file into the given scene structure. The diff --git a/third_party/libassimp/include/assimp/Bitmap.h b/third_party/libassimp/include/assimp/Bitmap.h index 2091168639..e6b5fb1327 100644 --- a/third_party/libassimp/include/assimp/Bitmap.h +++ b/third_party/libassimp/include/assimp/Bitmap.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/BlobIOSystem.h b/third_party/libassimp/include/assimp/BlobIOSystem.h index a0ed7209f1..d005e5c119 100644 --- a/third_party/libassimp/include/assimp/BlobIOSystem.h +++ b/third_party/libassimp/include/assimp/BlobIOSystem.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/ByteSwapper.h b/third_party/libassimp/include/assimp/ByteSwapper.h index 322a242dec..20a2463fb8 100644 --- a/third_party/libassimp/include/assimp/ByteSwapper.h +++ b/third_party/libassimp/include/assimp/ByteSwapper.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/CreateAnimMesh.h b/third_party/libassimp/include/assimp/CreateAnimMesh.h index ad625cb9f1..a60173588f 100644 --- a/third_party/libassimp/include/assimp/CreateAnimMesh.h +++ b/third_party/libassimp/include/assimp/CreateAnimMesh.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/DefaultIOStream.h b/third_party/libassimp/include/assimp/DefaultIOStream.h index e0e010ecba..994d728ff5 100644 --- a/third_party/libassimp/include/assimp/DefaultIOStream.h +++ b/third_party/libassimp/include/assimp/DefaultIOStream.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/DefaultIOSystem.h b/third_party/libassimp/include/assimp/DefaultIOSystem.h index a5d45c692a..2dd5c801b5 100644 --- a/third_party/libassimp/include/assimp/DefaultIOSystem.h +++ b/third_party/libassimp/include/assimp/DefaultIOSystem.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/DefaultLogger.hpp b/third_party/libassimp/include/assimp/DefaultLogger.hpp index 1f0c899be7..1946e250a6 100644 --- a/third_party/libassimp/include/assimp/DefaultLogger.hpp +++ b/third_party/libassimp/include/assimp/DefaultLogger.hpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/Exporter.hpp b/third_party/libassimp/include/assimp/Exporter.hpp index 4e0843b602..ea0303e804 100644 --- a/third_party/libassimp/include/assimp/Exporter.hpp +++ b/third_party/libassimp/include/assimp/Exporter.hpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -190,7 +190,7 @@ public: * @note Use aiCopyScene() to get a modifiable copy of a previously * imported scene. */ const aiExportDataBlob* ExportToBlob(const aiScene* pScene, const char* pFormatId, - unsigned int pPreprocessing = 0u, const ExportProperties* = nullptr); + unsigned int pPreprocessing = 0u, const ExportProperties* pProperties = nullptr); const aiExportDataBlob* ExportToBlob( const aiScene* pScene, const std::string& pFormatId, unsigned int pPreprocessing = 0u, const ExportProperties* pProperties = nullptr); diff --git a/third_party/libassimp/include/assimp/GenericProperty.h b/third_party/libassimp/include/assimp/GenericProperty.h index 7b75cb1c87..183ecd5197 100644 --- a/third_party/libassimp/include/assimp/GenericProperty.h +++ b/third_party/libassimp/include/assimp/GenericProperty.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/Hash.h b/third_party/libassimp/include/assimp/Hash.h index eb5df757d9..30657be198 100644 --- a/third_party/libassimp/include/assimp/Hash.h +++ b/third_party/libassimp/include/assimp/Hash.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/IOStream.hpp b/third_party/libassimp/include/assimp/IOStream.hpp index 52b80cc158..0623d0f70b 100644 --- a/third_party/libassimp/include/assimp/IOStream.hpp +++ b/third_party/libassimp/include/assimp/IOStream.hpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/IOStreamBuffer.h b/third_party/libassimp/include/assimp/IOStreamBuffer.h index c93a191df6..58abd97a02 100644 --- a/third_party/libassimp/include/assimp/IOStreamBuffer.h +++ b/third_party/libassimp/include/assimp/IOStreamBuffer.h @@ -4,7 +4,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -243,7 +243,7 @@ template inline bool IOStreamBuffer::getNextDataLine( std::vector &buffer, T continuationToken ) { buffer.resize( m_cacheSize ); - if ( m_cachePos == m_cacheSize || 0 == m_filePos ) { + if ( m_cachePos >= m_cacheSize || 0 == m_filePos ) { if ( !readNextBlock() ) { return false; } @@ -273,6 +273,9 @@ bool IOStreamBuffer::getNextDataLine( std::vector &buffer, T continuationT buffer[ i ] = m_cache[ m_cachePos ]; ++m_cachePos; ++i; + if (m_cachePos >= size()) { + break; + } if ( m_cachePos >= m_cacheSize ) { if ( !readNextBlock() ) { return false; diff --git a/third_party/libassimp/include/assimp/IOSystem.hpp b/third_party/libassimp/include/assimp/IOSystem.hpp index a36e225084..78139c2839 100644 --- a/third_party/libassimp/include/assimp/IOSystem.hpp +++ b/third_party/libassimp/include/assimp/IOSystem.hpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/Importer.hpp b/third_party/libassimp/include/assimp/Importer.hpp index 1d1dac19fe..4941df4122 100644 --- a/third_party/libassimp/include/assimp/Importer.hpp +++ b/third_party/libassimp/include/assimp/Importer.hpp @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/LineSplitter.h b/third_party/libassimp/include/assimp/LineSplitter.h index eb6b6e46c1..4afe45b92a 100644 --- a/third_party/libassimp/include/assimp/LineSplitter.h +++ b/third_party/libassimp/include/assimp/LineSplitter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/LogAux.h b/third_party/libassimp/include/assimp/LogAux.h index cf6d500147..558485272e 100644 --- a/third_party/libassimp/include/assimp/LogAux.h +++ b/third_party/libassimp/include/assimp/LogAux.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/LogStream.hpp b/third_party/libassimp/include/assimp/LogStream.hpp index e0eb8d5051..d0281e2d02 100644 --- a/third_party/libassimp/include/assimp/LogStream.hpp +++ b/third_party/libassimp/include/assimp/LogStream.hpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/Logger.hpp b/third_party/libassimp/include/assimp/Logger.hpp index 6a9928735b..89cade6c33 100644 --- a/third_party/libassimp/include/assimp/Logger.hpp +++ b/third_party/libassimp/include/assimp/Logger.hpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/Macros.h b/third_party/libassimp/include/assimp/Macros.h index 3aaed4e975..6515303372 100644 --- a/third_party/libassimp/include/assimp/Macros.h +++ b/third_party/libassimp/include/assimp/Macros.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/MathFunctions.h b/third_party/libassimp/include/assimp/MathFunctions.h index cb3b696076..f49273bb34 100644 --- a/third_party/libassimp/include/assimp/MathFunctions.h +++ b/third_party/libassimp/include/assimp/MathFunctions.h @@ -39,22 +39,24 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ +#pragma once + /** @file MathFunctions.h - * @brief Implementation of the math functions (gcd and lcm) +* @brief Implementation of math utility functions. * - * Copied from BoostWorkaround/math - */ +*/ + +#include namespace Assimp { namespace Math { // TODO: use binary GCD for unsigned integers .... template < typename IntegerType > -IntegerType gcd( IntegerType a, IntegerType b ) -{ +inline +IntegerType gcd( IntegerType a, IntegerType b ) { const IntegerType zero = (IntegerType)0; - while ( true ) - { + while ( true ) { if ( a == zero ) return b; b %= a; @@ -66,12 +68,19 @@ IntegerType gcd( IntegerType a, IntegerType b ) } template < typename IntegerType > -IntegerType lcm( IntegerType a, IntegerType b ) -{ +inline +IntegerType lcm( IntegerType a, IntegerType b ) { const IntegerType t = gcd (a,b); - if (!t)return t; + if (!t) + return t; return a / t * b; } +template +inline +T getEpsilon() { + return std::numeric_limits::epsilon(); +} + } } diff --git a/third_party/libassimp/include/assimp/MemoryIOWrapper.h b/third_party/libassimp/include/assimp/MemoryIOWrapper.h index 5260cb2b2a..c522787184 100644 --- a/third_party/libassimp/include/assimp/MemoryIOWrapper.h +++ b/third_party/libassimp/include/assimp/MemoryIOWrapper.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -51,26 +51,23 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include namespace Assimp { + #define AI_MEMORYIO_MAGIC_FILENAME "$$$___magic___$$$" #define AI_MEMORYIO_MAGIC_FILENAME_LENGTH 17 // ---------------------------------------------------------------------------------- /** Implementation of IOStream to read directly from a memory buffer */ // ---------------------------------------------------------------------------------- -class MemoryIOStream : public IOStream -{ - //friend class MemoryIOSystem; +class MemoryIOStream : public IOStream { public: MemoryIOStream (const uint8_t* buff, size_t len, bool own = false) - : buffer (buff) - , length(len) - , pos((size_t)0) - , own(own) - { + : buffer (buff) + , length(len) + , pos((size_t)0) + , own(own) { + // empty } -public: - ~MemoryIOStream () { if(own) { delete[] buffer; @@ -80,11 +77,13 @@ public: // ------------------------------------------------------------------- // Read from stream size_t Read(void* pvBuffer, size_t pSize, size_t pCount) { - ai_assert(pvBuffer); - ai_assert(pSize); - const size_t cnt = std::min(pCount,(length-pos)/pSize), ofs = pSize*cnt; + ai_assert(nullptr != pvBuffer); + ai_assert(0 != pSize); + + const size_t cnt = std::min( pCount, (length-pos) / pSize); + const size_t ofs = pSize * cnt; - memcpy(pvBuffer,buffer+pos,ofs); + ::memcpy(pvBuffer,buffer+pos,ofs); pos += ofs; return cnt; @@ -105,14 +104,12 @@ public: return AI_FAILURE; } pos = pOffset; - } - else if (aiOrigin_END == pOrigin) { + } else if (aiOrigin_END == pOrigin) { if (pOffset > length) { return AI_FAILURE; } pos = length-pOffset; - } - else { + } else { if (pOffset+pos > length) { return AI_FAILURE; } @@ -147,12 +144,15 @@ private: // --------------------------------------------------------------------------- /** Dummy IO system to read from a memory buffer */ -class MemoryIOSystem : public IOSystem -{ +class MemoryIOSystem : public IOSystem { public: /** Constructor. */ - MemoryIOSystem (const uint8_t* buff, size_t len) - : buffer (buff), length(len) { + MemoryIOSystem(const uint8_t* buff, size_t len, IOSystem* io) + : buffer(buff) + , length(len) + , existing_io(io) + , created_streams() { + // empty } /** Destructor. */ @@ -161,41 +161,84 @@ public: // ------------------------------------------------------------------- /** Tests for the existence of a file at the given path. */ - bool Exists( const char* pFile) const { - return !strncmp(pFile,AI_MEMORYIO_MAGIC_FILENAME,AI_MEMORYIO_MAGIC_FILENAME_LENGTH); + bool Exists(const char* pFile) const override { + if (0 == strncmp( pFile, AI_MEMORYIO_MAGIC_FILENAME, AI_MEMORYIO_MAGIC_FILENAME_LENGTH ) ) { + return true; + } + return existing_io ? existing_io->Exists(pFile) : false; } // ------------------------------------------------------------------- /** Returns the directory separator. */ - char getOsSeparator() const { - return '/'; // why not? it doesn't care + char getOsSeparator() const override { + return existing_io ? existing_io->getOsSeparator() + : '/'; // why not? it doesn't care } // ------------------------------------------------------------------- /** Open a new file with a given path. */ - IOStream* Open( const char* pFile, const char* /*pMode*/ = "rb") { - if (strncmp(pFile,AI_MEMORYIO_MAGIC_FILENAME,AI_MEMORYIO_MAGIC_FILENAME_LENGTH)) { - return NULL; + IOStream* Open(const char* pFile, const char* pMode = "rb") override { + if ( 0 == strncmp( pFile, AI_MEMORYIO_MAGIC_FILENAME, AI_MEMORYIO_MAGIC_FILENAME_LENGTH ) ) { + created_streams.emplace_back(new MemoryIOStream(buffer, length)); + return created_streams.back(); } - return new MemoryIOStream(buffer,length); + return existing_io ? existing_io->Open(pFile, pMode) : NULL; } // ------------------------------------------------------------------- /** Closes the given file and releases all resources associated with it. */ - void Close( IOStream* pFile) { - delete pFile; + void Close( IOStream* pFile) override { + auto it = std::find(created_streams.begin(), created_streams.end(), pFile); + if (it != created_streams.end()) { + delete pFile; + created_streams.erase(it); + } else if (existing_io) { + existing_io->Close(pFile); + } } // ------------------------------------------------------------------- /** Compare two paths */ - bool ComparePaths (const char* /*one*/, const char* /*second*/) const { - return false; + bool ComparePaths(const char* one, const char* second) const override { + return existing_io ? existing_io->ComparePaths(one, second) : false; + } + + bool PushDirectory( const std::string &path ) override { + return existing_io ? existing_io->PushDirectory(path) : false; + } + + const std::string &CurrentDirectory() const override { + static std::string empty; + return existing_io ? existing_io->CurrentDirectory() : empty; + } + + size_t StackSize() const override { + return existing_io ? existing_io->StackSize() : 0; + } + + bool PopDirectory() override { + return existing_io ? existing_io->PopDirectory() : false; + } + + bool CreateDirectory( const std::string &path ) override { + return existing_io ? existing_io->CreateDirectory(path) : false; + } + + bool ChangeDirectory( const std::string &path ) override { + return existing_io ? existing_io->ChangeDirectory(path) : false; + } + + bool DeleteFile( const std::string &file ) override { + return existing_io ? existing_io->DeleteFile(file) : false; } private: const uint8_t* buffer; size_t length; + IOSystem* existing_io; + std::vector created_streams; }; + } // end namespace Assimp #endif diff --git a/third_party/libassimp/include/assimp/NullLogger.hpp b/third_party/libassimp/include/assimp/NullLogger.hpp index 776f301ab9..c45d01bd48 100644 --- a/third_party/libassimp/include/assimp/NullLogger.hpp +++ b/third_party/libassimp/include/assimp/NullLogger.hpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/ParsingUtils.h b/third_party/libassimp/include/assimp/ParsingUtils.h index 4553072db9..6b9574fc67 100644 --- a/third_party/libassimp/include/assimp/ParsingUtils.h +++ b/third_party/libassimp/include/assimp/ParsingUtils.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -196,8 +196,7 @@ bool GetNextLine( const char_t*& buffer, char_t out[ BufferSize ] ) { // --------------------------------------------------------------------------------- template -AI_FORCE_INLINE bool IsNumeric( char_t in) -{ +AI_FORCE_INLINE bool IsNumeric( char_t in) { return ( in >= '0' && in <= '9' ) || '-' == in || '+' == in; } diff --git a/third_party/libassimp/include/assimp/Profiler.h b/third_party/libassimp/include/assimp/Profiler.h index da5af27267..6ff9d41c0a 100644 --- a/third_party/libassimp/include/assimp/Profiler.h +++ b/third_party/libassimp/include/assimp/Profiler.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/ProgressHandler.hpp b/third_party/libassimp/include/assimp/ProgressHandler.hpp index f295eac39c..4e47f1d0a6 100644 --- a/third_party/libassimp/include/assimp/ProgressHandler.hpp +++ b/third_party/libassimp/include/assimp/ProgressHandler.hpp @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/RemoveComments.h b/third_party/libassimp/include/assimp/RemoveComments.h index 08299f22b9..404b496719 100644 --- a/third_party/libassimp/include/assimp/RemoveComments.h +++ b/third_party/libassimp/include/assimp/RemoveComments.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/SGSpatialSort.h b/third_party/libassimp/include/assimp/SGSpatialSort.h index 3c95d0b51f..5b4f3f41f2 100644 --- a/third_party/libassimp/include/assimp/SGSpatialSort.h +++ b/third_party/libassimp/include/assimp/SGSpatialSort.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/SceneCombiner.h b/third_party/libassimp/include/assimp/SceneCombiner.h index ec2788245f..f69a25f43b 100644 --- a/third_party/libassimp/include/assimp/SceneCombiner.h +++ b/third_party/libassimp/include/assimp/SceneCombiner.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -65,6 +65,7 @@ struct aiLight; struct aiMetadata; struct aiBone; struct aiMesh; +struct aiAnimMesh; struct aiAnimation; struct aiNodeAnim; @@ -363,6 +364,7 @@ public: static void Copy (aiMesh** dest, const aiMesh* src); // similar to Copy(): + static void Copy (aiAnimMesh** dest, const aiAnimMesh* src); static void Copy (aiMaterial** dest, const aiMaterial* src); static void Copy (aiTexture** dest, const aiTexture* src); static void Copy (aiAnimation** dest, const aiAnimation* src); diff --git a/third_party/libassimp/include/assimp/SkeletonMeshBuilder.h b/third_party/libassimp/include/assimp/SkeletonMeshBuilder.h index 993d9c84d6..f9b8d9f55c 100644 --- a/third_party/libassimp/include/assimp/SkeletonMeshBuilder.h +++ b/third_party/libassimp/include/assimp/SkeletonMeshBuilder.h @@ -4,7 +4,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/SmoothingGroups.h b/third_party/libassimp/include/assimp/SmoothingGroups.h index 88345c66a7..92d65cea02 100644 --- a/third_party/libassimp/include/assimp/SmoothingGroups.h +++ b/third_party/libassimp/include/assimp/SmoothingGroups.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/SpatialSort.h b/third_party/libassimp/include/assimp/SpatialSort.h index 8fb450841b..61b345bcbf 100644 --- a/third_party/libassimp/include/assimp/SpatialSort.h +++ b/third_party/libassimp/include/assimp/SpatialSort.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/StandardShapes.h b/third_party/libassimp/include/assimp/StandardShapes.h index fdf1b034d3..3791569b83 100644 --- a/third_party/libassimp/include/assimp/StandardShapes.h +++ b/third_party/libassimp/include/assimp/StandardShapes.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/StreamReader.h b/third_party/libassimp/include/assimp/StreamReader.h index b01ee4b661..9116c14261 100644 --- a/third_party/libassimp/include/assimp/StreamReader.h +++ b/third_party/libassimp/include/assimp/StreamReader.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -48,11 +48,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_STREAMREADER_H_INCLUDED #define AI_STREAMREADER_H_INCLUDED +#include +#include + #include "ByteSwapper.h" #include "Exceptional.h" #include -#include -#include namespace Assimp { @@ -314,7 +315,7 @@ private: const size_t read = stream->Read(current,1,s); // (read < s) can only happen if the stream was opened in text mode, in which case FileSize() is not reliable ai_assert(read <= s); - end = limit = &buffer[read]; + end = limit = &buffer[read-1] + 1; } private: diff --git a/third_party/libassimp/include/assimp/StreamWriter.h b/third_party/libassimp/include/assimp/StreamWriter.h index deb35fb4d9..c7cf6c0d74 100644 --- a/third_party/libassimp/include/assimp/StreamWriter.h +++ b/third_party/libassimp/include/assimp/StreamWriter.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/StringComparison.h b/third_party/libassimp/include/assimp/StringComparison.h index aea7f001a6..8acef277b9 100644 --- a/third_party/libassimp/include/assimp/StringComparison.h +++ b/third_party/libassimp/include/assimp/StringComparison.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/StringUtils.h b/third_party/libassimp/include/assimp/StringUtils.h index 906898b539..d68b7fa479 100644 --- a/third_party/libassimp/include/assimp/StringUtils.h +++ b/third_party/libassimp/include/assimp/StringUtils.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/Subdivision.h b/third_party/libassimp/include/assimp/Subdivision.h index 84aff68f11..43feb73b30 100644 --- a/third_party/libassimp/include/assimp/Subdivision.h +++ b/third_party/libassimp/include/assimp/Subdivision.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/TinyFormatter.h b/third_party/libassimp/include/assimp/TinyFormatter.h index 2ddc227e98..1226b482e6 100644 --- a/third_party/libassimp/include/assimp/TinyFormatter.h +++ b/third_party/libassimp/include/assimp/TinyFormatter.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/Vertex.h b/third_party/libassimp/include/assimp/Vertex.h index f1c02ee070..2a7f0256ad 100644 --- a/third_party/libassimp/include/assimp/Vertex.h +++ b/third_party/libassimp/include/assimp/Vertex.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/XMLTools.h b/third_party/libassimp/include/assimp/XMLTools.h index 4b76c44839..b0d3276873 100644 --- a/third_party/libassimp/include/assimp/XMLTools.h +++ b/third_party/libassimp/include/assimp/XMLTools.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/ZipArchiveIOSystem.h b/third_party/libassimp/include/assimp/ZipArchiveIOSystem.h new file mode 100644 index 0000000000..38cbbf2a71 --- /dev/null +++ b/third_party/libassimp/include/assimp/ZipArchiveIOSystem.h @@ -0,0 +1,87 @@ +/* +--------------------------------------------------------------------------- +Open Asset Import Library (assimp) +--------------------------------------------------------------------------- + +Copyright (c) 2006-2019, 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 ZipArchiveIOSystem.h + * @brief Implementation of IOSystem to read a ZIP file from another IOSystem +*/ + +#ifndef AI_ZIPARCHIVEIOSYSTEM_H_INC +#define AI_ZIPARCHIVEIOSYSTEM_H_INC + +#include +#include + +namespace Assimp { + class ZipArchiveIOSystem : public IOSystem { + public: + //! Open a Zip using the proffered IOSystem + ZipArchiveIOSystem(IOSystem* pIOHandler, const char *pFilename, const char* pMode = "r"); + ZipArchiveIOSystem(IOSystem* pIOHandler, const std::string& rFilename, const char* pMode = "r"); + virtual ~ZipArchiveIOSystem(); + bool Exists(const char* pFilename) const override; + char getOsSeparator() const override; + IOStream* Open(const char* pFilename, const char* pMode = "rb") override; + void Close(IOStream* pFile) override; + + // Specific to ZIP + //! The file was opened and is a ZIP + bool isOpen() const; + + //! Get the list of all files with their simplified paths + //! Intended for use within Assimp library boundaries + void getFileList(std::vector& rFileList) const; + + //! Get the list of all files with extension (must be lowercase) + //! Intended for use within Assimp library boundaries + void getFileListExtension(std::vector& rFileList, const std::string& extension) const; + + static bool isZipArchive(IOSystem* pIOHandler, const char *pFilename); + static bool isZipArchive(IOSystem* pIOHandler, const std::string& rFilename); + + private: + class Implement; + Implement *pImpl = nullptr; + }; +} // Namespace Assimp + +#endif // AI_ZIPARCHIVEIOSYSTEM_H_INC diff --git a/third_party/libassimp/code/ScaleProcess.cpp b/third_party/libassimp/include/assimp/aabb.h similarity index 50% rename from third_party/libassimp/code/ScaleProcess.cpp rename to third_party/libassimp/include/assimp/aabb.h index facc39d7d2..a20f317424 100644 --- a/third_party/libassimp/code/ScaleProcess.cpp +++ b/third_party/libassimp/include/assimp/aabb.h @@ -1,15 +1,17 @@ /* +--------------------------------------------------------------------------- Open Asset Import Library (assimp) ----------------------------------------------------------------------- +--------------------------------------------------------------------------- + +Copyright (c) 2006-2019, assimp team -Copyright (c) 2006-2018, 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: +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 @@ -36,68 +38,39 @@ 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. - ----------------------------------------------------------------------- +--------------------------------------------------------------------------- */ -#ifndef ASSIMP_BUILD_NO_GLOBALSCALE_PROCESS -#include "ScaleProcess.h" +#pragma once +#ifndef AI_AABB_H_INC +#define AI_AABB_H_INC -#include -#include +#include -namespace Assimp { +struct aiAABB { + C_STRUCT aiVector3D mMin; + C_STRUCT aiVector3D mMax; -ScaleProcess::ScaleProcess() -: BaseProcess() -, mScale( AI_CONFIG_GLOBAL_SCALE_FACTOR_DEFAULT ) { - // empty -} +#ifdef __cplusplus -ScaleProcess::~ScaleProcess() { - // empty -} - -void ScaleProcess::setScale( ai_real scale ) { - mScale = scale; -} - -ai_real ScaleProcess::getScale() const { - return mScale; -} - -bool ScaleProcess::IsActive( unsigned int pFlags ) const { - return ( pFlags & aiProcess_GlobalScale ) != 0; -} - -void ScaleProcess::SetupProperties( const Importer* pImp ) { - mScale = pImp->GetPropertyFloat( AI_CONFIG_GLOBAL_SCALE_FACTOR_KEY, 0 ); -} - -void ScaleProcess::Execute( aiScene* pScene ) { - if ( nullptr == pScene ) { - return; + aiAABB() + : mMin() + , mMax() { + // empty } - if ( nullptr == pScene->mRootNode ) { - return; + aiAABB(const aiVector3D &min, const aiVector3D &max ) + : mMin(min) + , mMax(max) { + // empty } - traverseNodes( pScene->mRootNode ); -} - -void ScaleProcess::traverseNodes( aiNode *node ) { - applyScaling( node ); -} - -void ScaleProcess::applyScaling( aiNode *currentNode ) { - if ( nullptr != currentNode ) { - currentNode->mTransformation.a1 = currentNode->mTransformation.a1 * mScale; - currentNode->mTransformation.b2 = currentNode->mTransformation.b2 * mScale; - currentNode->mTransformation.c3 = currentNode->mTransformation.c3 * mScale; + ~aiAABB() { + // empty } -} -} // Namespace Assimp +#endif +}; -#endif // !! ASSIMP_BUILD_NO_GLOBALSCALE_PROCESS + +#endif diff --git a/third_party/libassimp/include/assimp/ai_assert.h b/third_party/libassimp/include/assimp/ai_assert.h index 7752763db4..e5de5d3f36 100644 --- a/third_party/libassimp/include/assimp/ai_assert.h +++ b/third_party/libassimp/include/assimp/ai_assert.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -46,9 +46,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifdef ASSIMP_BUILD_DEBUG # include -# define ai_assert(expression) assert(expression) +# define ai_assert(expression) assert( expression ) +# define ai_assert_entry() assert( false ) #else # define ai_assert(expression) -#endif // +# define ai_assert_entry() +#endif // ASSIMP_BUILD_DEBUG #endif // AI_ASSERT_H_INC + diff --git a/third_party/libassimp/include/assimp/anim.h b/third_party/libassimp/include/assimp/anim.h index 8a09841928..02e92739ec 100644 --- a/third_party/libassimp/include/assimp/anim.h +++ b/third_party/libassimp/include/assimp/anim.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/camera.h b/third_party/libassimp/include/assimp/camera.h index 6fea5a7d70..a9a9f76533 100644 --- a/third_party/libassimp/include/assimp/camera.h +++ b/third_party/libassimp/include/assimp/camera.h @@ -3,9 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team - - +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -60,7 +58,7 @@ extern "C" { * * Cameras have a representation in the node graph and can be animated. * An important aspect is that the camera itself is also part of the - * scenegraph. This means, any values such as the look-at vector are not + * scene-graph. This means, any values such as the look-at vector are not * *absolute*, they're relative to the coordinate system defined * by the node which corresponds to the camera. This allows for camera * animations. For static cameras parameters like the 'look-at' or 'up' vectors @@ -115,7 +113,6 @@ struct aiCamera */ C_STRUCT aiVector3D mPosition; - /** 'Up' - vector of the camera coordinate system relative to * the coordinate space defined by the corresponding node. * @@ -136,7 +133,6 @@ struct aiCamera */ C_STRUCT aiVector3D mLookAt; - /** Half horizontal field of view angle, in radians. * * The field of view angle is the angle between the center @@ -162,7 +158,6 @@ struct aiCamera */ float mClipPlaneFar; - /** Screen aspect ratio. * * This is the ration between the width and the height of the diff --git a/third_party/libassimp/include/assimp/cfileio.h b/third_party/libassimp/include/assimp/cfileio.h index a7a56f81c8..8f7ca45469 100644 --- a/third_party/libassimp/include/assimp/cfileio.h +++ b/third_party/libassimp/include/assimp/cfileio.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/cimport.h b/third_party/libassimp/include/assimp/cimport.h index eb1e6e0d4e..dbd10f1370 100644 --- a/third_party/libassimp/include/assimp/cimport.h +++ b/third_party/libassimp/include/assimp/cimport.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/color4.h b/third_party/libassimp/include/assimp/color4.h index fddd1b638c..3c97c8eda2 100644 --- a/third_party/libassimp/include/assimp/color4.h +++ b/third_party/libassimp/include/assimp/color4.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/color4.inl b/third_party/libassimp/include/assimp/color4.inl index 6e27292b99..afa53dcb5b 100644 --- a/third_party/libassimp/include/assimp/color4.inl +++ b/third_party/libassimp/include/assimp/color4.inl @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -85,6 +85,8 @@ AI_FORCE_INLINE TReal aiColor4t::operator[](unsigned int i) const { return g; case 2: return b; + case 3: + return a; default: break; } @@ -100,6 +102,8 @@ AI_FORCE_INLINE TReal& aiColor4t::operator[](unsigned int i) { return g; case 2: return b; + case 3: + return a; default: break; } diff --git a/third_party/libassimp/include/assimp/config.h b/third_party/libassimp/include/assimp/config.h index fe8e901522..48d61941ad 100644 --- a/third_party/libassimp/include/assimp/config.h +++ b/third_party/libassimp/include/assimp/config.h @@ -498,6 +498,13 @@ enum aiComponent #define AI_CONFIG_PP_FID_ANIM_ACCURACY \ "PP_FID_ANIM_ACCURACY" +// --------------------------------------------------------------------------- +/** @brief Input parameter to the #aiProcess_FindInvalidData step: + * Set to true to ignore texture coordinates. This may be useful if you have + * to assign different kind of textures like one for the summer or one for the winter. + */ +#define AI_CONFIG_PP_FID_IGNORE_TEXTURECOORDS \ + "PP_FID_IGNORE_TEXTURECOORDS" // TransformUVCoords evaluates UV scalings #define AI_UVTRAFO_SCALING 0x1 @@ -644,13 +651,28 @@ enum aiComponent // --------------------------------------------------------------------------- /** @brief Set whether the fbx importer will use the legacy embedded texture naming. -* -* The default value is false (0) -* Property type: bool -*/ + * + * The default value is false (0) + * Property type: bool + */ #define AI_CONFIG_IMPORT_FBX_EMBEDDED_TEXTURES_LEGACY_NAMING \ "AI_CONFIG_IMPORT_FBX_EMBEDDED_TEXTURES_LEGACY_NAMING" - + +// --------------------------------------------------------------------------- +/** @brief Set wether the importer shall not remove empty bones. + * + * Empty bone are often used to define connections for other models. + */ +#define AI_CONFIG_IMPORT_REMOVE_EMPTY_BONES \ + "AI_CONFIG_IMPORT_REMOVE_EMPTY_BONES" + + +// --------------------------------------------------------------------------- +/** @brief Set wether the FBX importer shall convert the unit from cm to m. + */ +#define AI_CONFIG_FBX_CONVERT_TO_M \ + "AI_CONFIG_FBX_CONVERT_TO_M" + // --------------------------------------------------------------------------- /** @brief Set the vertex animation keyframe to be imported * @@ -959,8 +981,12 @@ enum aiComponent #define AI_CONFIG_EXPORT_XFILE_64BIT "EXPORT_XFILE_64BIT" -/** - * +/** @brief Specifies whether the assimp export shall be able to export point clouds + * + * When this flag is not defined the render data has to contain valid faces. + * Point clouds are only a collection of vertices which have nor spatial organization + * by a face and the validation process will remove them. Enabling this feature will + * switch off the flag and enable the functionality to export pure point clouds. */ #define AI_CONFIG_EXPORT_POINT_CLOUDS "EXPORT_POINT_CLOUDS" @@ -973,6 +999,13 @@ enum aiComponent # define AI_CONFIG_GLOBAL_SCALE_FACTOR_DEFAULT 1.0f #endif // !! AI_DEBONE_THRESHOLD +#define AI_CONFIG_APP_SCALE_KEY "APP_SCALE_FACTOR" + +#if (!defined AI_CONFIG_APP_SCALE_KEY) +# define AI_CONFIG_APP_SCALE_KEY 1.0 +#endif // AI_CONFIG_APP_SCALE_KEY + + // ---------- All the Build/Compile-time defines ------------ /** @brief Specifies if double precision is supported inside assimp diff --git a/third_party/libassimp/include/assimp/config.h.in b/third_party/libassimp/include/assimp/config.h.in index fd828bc6e9..3a6379bf40 100644 --- a/third_party/libassimp/include/assimp/config.h.in +++ b/third_party/libassimp/include/assimp/config.h.in @@ -498,6 +498,13 @@ enum aiComponent #define AI_CONFIG_PP_FID_ANIM_ACCURACY \ "PP_FID_ANIM_ACCURACY" +// --------------------------------------------------------------------------- +/** @brief Input parameter to the #aiProcess_FindInvalidData step: + * Set to true to ignore texture coordinates. This may be useful if you have + * to assign different kind of textures like one for the summer or one for the winter. + */ +#define AI_CONFIG_PP_FID_IGNORE_TEXTURECOORDS \ + "PP_FID_IGNORE_TEXTURECOORDS" // TransformUVCoords evaluates UV scalings #define AI_UVTRAFO_SCALING 0x1 @@ -644,13 +651,28 @@ enum aiComponent // --------------------------------------------------------------------------- /** @brief Set whether the fbx importer will use the legacy embedded texture naming. -* -* The default value is false (0) -* Property type: bool -*/ + * + * The default value is false (0) + * Property type: bool + */ #define AI_CONFIG_IMPORT_FBX_EMBEDDED_TEXTURES_LEGACY_NAMING \ "AI_CONFIG_IMPORT_FBX_EMBEDDED_TEXTURES_LEGACY_NAMING" - + +// --------------------------------------------------------------------------- +/** @brief Set wether the importer shall not remove empty bones. + * + * Empty bone are often used to define connections for other models. + */ +#define AI_CONFIG_IMPORT_REMOVE_EMPTY_BONES \ + "AI_CONFIG_IMPORT_REMOVE_EMPTY_BONES" + + +// --------------------------------------------------------------------------- +/** @brief Set wether the FBX importer shall convert the unit from cm to m. + */ +#define AI_CONFIG_FBX_CONVERT_TO_M \ + "AI_CONFIG_FBX_CONVERT_TO_M" + // --------------------------------------------------------------------------- /** @brief Set the vertex animation keyframe to be imported * @@ -959,8 +981,12 @@ enum aiComponent #define AI_CONFIG_EXPORT_XFILE_64BIT "EXPORT_XFILE_64BIT" -/** - * +/** @brief Specifies whether the assimp export shall be able to export point clouds + * + * When this flag is not defined the render data has to contain valid faces. + * Point clouds are only a collection of vertices which have nor spatial organization + * by a face and the validation process will remove them. Enabling this feature will + * switch off the flag and enable the functionality to export pure point clouds. */ #define AI_CONFIG_EXPORT_POINT_CLOUDS "EXPORT_POINT_CLOUDS" @@ -973,6 +999,13 @@ enum aiComponent # define AI_CONFIG_GLOBAL_SCALE_FACTOR_DEFAULT 1.0f #endif // !! AI_DEBONE_THRESHOLD +#define AI_CONFIG_APP_SCALE_KEY "APP_SCALE_FACTOR" + +#if (!defined AI_CONFIG_APP_SCALE_KEY) +# define AI_CONFIG_APP_SCALE_KEY 1.0 +#endif // AI_CONFIG_APP_SCALE_KEY + + // ---------- All the Build/Compile-time defines ------------ /** @brief Specifies if double precision is supported inside assimp diff --git a/third_party/libassimp/include/assimp/defs.h b/third_party/libassimp/include/assimp/defs.h index e651a1f7b9..05a5e3fd4b 100644 --- a/third_party/libassimp/include/assimp/defs.h +++ b/third_party/libassimp/include/assimp/defs.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -122,7 +122,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * OPTIMIZEANIMS * OPTIMIZEGRAPH * GENENTITYMESHES - * FIXTEXTUREPATHS */ + * FIXTEXTUREPATHS + * GENBOUNDINGBOXES */ ////////////////////////////////////////////////////////////////////////// #ifdef _MSC_VER @@ -214,10 +215,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endif #if (defined(__BORLANDC__) || defined (__BCPLUSPLUS__)) -#error Currently, Borland is unsupported. Feel free to port Assimp. - -// "W8059 Packgröße der Struktur geändert" - +# error Currently, Borland is unsupported. Feel free to port Assimp. #endif @@ -243,10 +241,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. typedef double ai_real; typedef signed long long int ai_int; typedef unsigned long long int ai_uint; +#ifndef ASSIMP_AI_REAL_TEXT_PRECISION +#define ASSIMP_AI_REAL_TEXT_PRECISION 16 +#endif // ASSIMP_AI_REAL_TEXT_PRECISION #else // ASSIMP_DOUBLE_PRECISION typedef float ai_real; typedef signed int ai_int; typedef unsigned int ai_uint; +#ifndef ASSIMP_AI_REAL_TEXT_PRECISION +#define ASSIMP_AI_REAL_TEXT_PRECISION 8 +#endif // ASSIMP_AI_REAL_TEXT_PRECISION #endif // ASSIMP_DOUBLE_PRECISION ////////////////////////////////////////////////////////////////////////// @@ -267,6 +271,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define AI_DEG_TO_RAD(x) ((x)*(ai_real)0.0174532925) #define AI_RAD_TO_DEG(x) ((x)*(ai_real)57.2957795) +/* Numerical limits */ +static const ai_real ai_epsilon = (ai_real) 0.00001; + /* Support for big-endian builds */ #if defined(__BYTE_ORDER__) # if (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) @@ -293,11 +300,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef _MSC_VER # define AI_NO_EXCEPT noexcept #else -# if (_MSC_VER == 1915 ) +# if (_MSC_VER >= 1915 ) # define AI_NO_EXCEPT noexcept # else # define AI_NO_EXCEPT # endif -#endif +#endif // _MSC_VER #endif // !! AI_DEFINES_H_INC diff --git a/third_party/libassimp/include/assimp/importerdesc.h b/third_party/libassimp/include/assimp/importerdesc.h index 36b773e455..36e387f011 100644 --- a/third_party/libassimp/include/assimp/importerdesc.h +++ b/third_party/libassimp/include/assimp/importerdesc.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/irrXMLWrapper.h b/third_party/libassimp/include/assimp/irrXMLWrapper.h index 296f26a328..77cfd5e47d 100644 --- a/third_party/libassimp/include/assimp/irrXMLWrapper.h +++ b/third_party/libassimp/include/assimp/irrXMLWrapper.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -44,7 +44,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define INCLUDED_AI_IRRXML_WRAPPER // some long includes .... -#include +#ifdef ASSIMP_USE_HUNTER +# include +#else +# include +#endif #include "IOStream.hpp" #include "BaseImporter.h" #include @@ -91,14 +95,15 @@ public: stream->Read(&data[0],data.size(),1); // Remove null characters from the input sequence otherwise the parsing will utterly fail - unsigned int size = 0; - unsigned int size_max = static_cast(data.size()); - for(unsigned int i = 0; i < size_max; i++) { - if(data[i] != '\0') { - data[size++] = data[i]; - } + // std::find is usually much faster than manually iterating + // It is very unlikely that there will be any null characters + auto null_char_iter = std::find(data.begin(), data.end(), '\0'); + + while (null_char_iter != data.end()) + { + null_char_iter = data.erase(null_char_iter); + null_char_iter = std::find(null_char_iter, data.end(), '\0'); } - data.resize(size); BaseImporter::ConvertToUTF8(data); } diff --git a/third_party/libassimp/include/assimp/light.h b/third_party/libassimp/include/assimp/light.h index dc0b8a4b63..1667cfb8c1 100644 --- a/third_party/libassimp/include/assimp/light.h +++ b/third_party/libassimp/include/assimp/light.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/material.h b/third_party/libassimp/include/assimp/material.h index 45b4844a3b..206eb2a2b0 100644 --- a/third_party/libassimp/include/assimp/material.h +++ b/third_party/libassimp/include/assimp/material.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -196,36 +196,40 @@ enum aiTextureType * (#aiMaterialProperty::mSemantic) for all material properties * *not* related to textures. */ - aiTextureType_NONE = 0x0, - + aiTextureType_NONE = 0, + /** LEGACY API MATERIALS + * Legacy refers to materials which + * Were originally implemented in the specifications around 2000. + * These must never be removed, as most engines support them. + */ /** The texture is combined with the result of the diffuse * lighting equation. */ - aiTextureType_DIFFUSE = 0x1, + aiTextureType_DIFFUSE = 1, /** The texture is combined with the result of the specular * lighting equation. */ - aiTextureType_SPECULAR = 0x2, + aiTextureType_SPECULAR = 2, /** The texture is combined with the result of the ambient * lighting equation. */ - aiTextureType_AMBIENT = 0x3, + aiTextureType_AMBIENT = 3, /** The texture is added to the result of the lighting * calculation. It isn't influenced by incoming light. */ - aiTextureType_EMISSIVE = 0x4, + aiTextureType_EMISSIVE = 4, /** The texture is a height map. * * By convention, higher gray-scale values stand for * higher elevations from the base height. */ - aiTextureType_HEIGHT = 0x5, + aiTextureType_HEIGHT = 5, /** The texture is a (tangent space) normal-map. * @@ -233,7 +237,7 @@ enum aiTextureType * normal maps. Assimp does (intentionally) not * distinguish here. */ - aiTextureType_NORMALS = 0x6, + aiTextureType_NORMALS = 6, /** The texture defines the glossiness of the material. * @@ -242,21 +246,21 @@ enum aiTextureType * function defined to map the linear color values in the * texture to a suitable exponent. Have fun. */ - aiTextureType_SHININESS = 0x7, + aiTextureType_SHININESS = 7, /** The texture defines per-pixel opacity. * * Usually 'white' means opaque and 'black' means * 'transparency'. Or quite the opposite. Have fun. */ - aiTextureType_OPACITY = 0x8, + aiTextureType_OPACITY = 8, /** Displacement texture * * The exact purpose and format is application-dependent. * Higher color values stand for higher vertex displacements. */ - aiTextureType_DISPLACEMENT = 0x9, + aiTextureType_DISPLACEMENT = 9, /** Lightmap texture (aka Ambient Occlusion) * @@ -265,22 +269,36 @@ enum aiTextureType * scaling value for the final color value of a pixel. Its * intensity is not affected by incoming light. */ - aiTextureType_LIGHTMAP = 0xA, + aiTextureType_LIGHTMAP = 10, /** Reflection texture * * Contains the color of a perfect mirror reflection. * Rarely used, almost never for real-time applications. */ - aiTextureType_REFLECTION = 0xB, + aiTextureType_REFLECTION = 11, + + /** PBR Materials + * PBR definitions from maya and other modelling packages now use this standard. + * This was originally introduced around 2012. + * Support for this is in game engines like Godot, Unreal or Unity3D. + * Modelling packages which use this are very common now. + */ + + aiTextureType_BASE_COLOR = 12, + aiTextureType_NORMAL_CAMERA = 13, + aiTextureType_EMISSION_COLOR = 14, + aiTextureType_METALNESS = 15, + aiTextureType_DIFFUSE_ROUGHNESS = 16, + aiTextureType_AMBIENT_OCCLUSION = 17, /** Unknown texture * * A texture reference that does not match any of the definitions * above is considered to be 'unknown'. It is still imported, - * but is excluded from any further postprocessing. + * but is excluded from any further post-processing. */ - aiTextureType_UNKNOWN = 0xC, + aiTextureType_UNKNOWN = 18, #ifndef SWIG @@ -375,7 +393,7 @@ enum aiShadingMode */ enum aiTextureFlags { - /** The texture's color values have to be inverted (componentwise 1-n) + /** The texture's color values have to be inverted (component-wise 1-n) */ aiTextureFlags_Invert = 0x1, @@ -902,6 +920,7 @@ extern "C" { #define AI_MATKEY_ENABLE_WIREFRAME "$mat.wireframe",0,0 #define AI_MATKEY_BLEND_FUNC "$mat.blend",0,0 #define AI_MATKEY_OPACITY "$mat.opacity",0,0 +#define AI_MATKEY_TRANSPARENCYFACTOR "$mat.transparencyfactor",0,0 #define AI_MATKEY_BUMPSCALING "$mat.bumpscaling",0,0 #define AI_MATKEY_SHININESS "$mat.shininess",0,0 #define AI_MATKEY_REFLECTIVITY "$mat.reflectivity",0,0 @@ -914,6 +933,13 @@ extern "C" { #define AI_MATKEY_COLOR_TRANSPARENT "$clr.transparent",0,0 #define AI_MATKEY_COLOR_REFLECTIVE "$clr.reflective",0,0 #define AI_MATKEY_GLOBAL_BACKGROUND_IMAGE "?bg.global",0,0 +#define AI_MATKEY_GLOBAL_SHADERLANG "?sh.lang",0,0 +#define AI_MATKEY_SHADER_VERTEX "?sh.vs",0,0 +#define AI_MATKEY_SHADER_FRAGMENT "?sh.fs",0,0 +#define AI_MATKEY_SHADER_GEO "?sh.gs",0,0 +#define AI_MATKEY_SHADER_TESSELATION "?sh.ts",0,0 +#define AI_MATKEY_SHADER_PRIMITIVE "?sh.ps",0,0 +#define AI_MATKEY_SHADER_COMPUTE "?sh.cs",0,0 // --------------------------------------------------------------------------- // Pure key names for all texture-related properties @@ -1457,8 +1483,6 @@ inline aiReturn aiGetMaterialInteger(const C_STRUCT aiMaterial* pMat, #endif //!__cplusplus - - // --------------------------------------------------------------------------- /** @brief Retrieve a color value from the material property table * diff --git a/third_party/libassimp/include/assimp/material.inl b/third_party/libassimp/include/assimp/material.inl index 3d4b07c069..b05d6af6c3 100644 --- a/third_party/libassimp/include/assimp/material.inl +++ b/third_party/libassimp/include/assimp/material.inl @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/matrix3x3.h b/third_party/libassimp/include/assimp/matrix3x3.h index 4bb55ad21a..22b69561ff 100644 --- a/third_party/libassimp/include/assimp/matrix3x3.h +++ b/third_party/libassimp/include/assimp/matrix3x3.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/matrix3x3.inl b/third_party/libassimp/include/assimp/matrix3x3.inl index ab2cc410ba..d9d45a3e92 100644 --- a/third_party/libassimp/include/assimp/matrix3x3.inl +++ b/third_party/libassimp/include/assimp/matrix3x3.inl @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/matrix4x4.h b/third_party/libassimp/include/assimp/matrix4x4.h index bfa9d38658..046bb535f2 100644 --- a/third_party/libassimp/include/assimp/matrix4x4.h +++ b/third_party/libassimp/include/assimp/matrix4x4.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/matrix4x4.inl b/third_party/libassimp/include/assimp/matrix4x4.inl index 680d7666df..19e684917b 100644 --- a/third_party/libassimp/include/assimp/matrix4x4.inl +++ b/third_party/libassimp/include/assimp/matrix4x4.inl @@ -3,9 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team - - +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -53,6 +51,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "matrix4x4.h" #include "matrix3x3.h" #include "quaternion.h" +#include "MathFunctions.h" #include #include @@ -420,8 +419,8 @@ inline void aiMatrix4x4t::Decompose (aiVector3t& pScaling, aiQuate } template -inline void aiMatrix4x4t::Decompose(aiVector3t& pScaling, aiVector3t& pRotation, aiVector3t& pPosition) const -{ +inline +void aiMatrix4x4t::Decompose(aiVector3t& pScaling, aiVector3t& pRotation, aiVector3t& pPosition) const { ASSIMP_MATRIX4_4_DECOMPOSE_PART; /* @@ -442,7 +441,7 @@ inline void aiMatrix4x4t::Decompose(aiVector3t& pScaling, aiVector */ // Use a small epsilon to solve floating-point inaccuracies - const TReal epsilon = 10e-3f; + const TReal epsilon = Assimp::Math::getEpsilon(); pRotation.y = std::asin(-vCols[0].z);// D. Angle around oY. diff --git a/third_party/libassimp/include/assimp/mesh.h b/third_party/libassimp/include/assimp/mesh.h index f47d5fd002..f1628f1f54 100644 --- a/third_party/libassimp/include/assimp/mesh.h +++ b/third_party/libassimp/include/assimp/mesh.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -48,7 +48,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef AI_MESH_H_INC #define AI_MESH_H_INC -#include "types.h" +#include +#include #ifdef __cplusplus extern "C" { @@ -402,7 +403,7 @@ enum aiPrimitiveType // --------------------------------------------------------------------------- -/** @brief NOT CURRENTLY IN USE. An AnimMesh is an attachment to an #aiMesh stores per-vertex +/** @brief An AnimMesh is an attachment to an #aiMesh stores per-vertex * animations for a particular frame. * * You may think of an #aiAnimMesh as a `patch` for the host mesh, which @@ -414,6 +415,9 @@ enum aiPrimitiveType */ struct aiAnimMesh { + /**Anim Mesh name */ + C_STRUCT aiString mName; + /** Replacement for aiMesh::mVertices. If this array is non-NULL, * it *must* contain mNumVertices entries. The corresponding * array in the host mesh must be non-NULL as well - animation @@ -466,10 +470,10 @@ struct aiAnimMesh { // fixme consider moving this to the ctor initializer list as well for( unsigned int a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; a++){ - mTextureCoords[a] = NULL; + mTextureCoords[a] = nullptr; } for( unsigned int a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; a++) { - mColors[a] = NULL; + mColors[a] = nullptr; } } @@ -490,34 +494,34 @@ struct aiAnimMesh /** Check whether the anim mesh overrides the vertex positions * of its host mesh*/ bool HasPositions() const { - return mVertices != NULL; + return mVertices != nullptr; } /** Check whether the anim mesh overrides the vertex normals * of its host mesh*/ bool HasNormals() const { - return mNormals != NULL; + return mNormals != nullptr; } /** Check whether the anim mesh overrides the vertex tangents * and bitangents of its host mesh. As for aiMesh, * tangents and bitangents always go together. */ bool HasTangentsAndBitangents() const { - return mTangents != NULL; + return mTangents != nullptr; } /** Check whether the anim mesh overrides a particular * set of vertex colors on his host mesh. * @param pIndex 0= AI_MAX_NUMBER_OF_COLOR_SETS ? false : mColors[pIndex] != NULL; + return pIndex >= AI_MAX_NUMBER_OF_COLOR_SETS ? false : mColors[pIndex] != nullptr; } /** Check whether the anim mesh overrides a particular * set of texture coordinates on his host mesh. * @param pIndex 0= AI_MAX_NUMBER_OF_TEXTURECOORDS ? false : mTextureCoords[pIndex] != NULL; + return pIndex >= AI_MAX_NUMBER_OF_TEXTURECOORDS ? false : mTextureCoords[pIndex] != nullptr; } #endif @@ -711,6 +715,11 @@ struct aiMesh * Method of morphing when animeshes are specified. */ unsigned int mMethod; + + /** + * + */ + C_STRUCT aiAABB mAABB; #ifdef __cplusplus @@ -732,7 +741,8 @@ struct aiMesh , mMaterialIndex( 0 ) , mNumAnimMeshes( 0 ) , mAnimMeshes(nullptr) - , mMethod( 0 ) { + , mMethod( 0 ) + , mAABB() { for( unsigned int a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a ) { mNumUVComponents[a] = 0; mTextureCoords[a] = nullptr; diff --git a/third_party/libassimp/include/assimp/metadata.h b/third_party/libassimp/include/assimp/metadata.h index 498e2f6d1c..3a1dd1442a 100644 --- a/third_party/libassimp/include/assimp/metadata.h +++ b/third_party/libassimp/include/assimp/metadata.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/pbrmaterial.h b/third_party/libassimp/include/assimp/pbrmaterial.h index 723957300b..ce5f822173 100644 --- a/third_party/libassimp/include/assimp/pbrmaterial.h +++ b/third_party/libassimp/include/assimp/pbrmaterial.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/postprocess.h b/third_party/libassimp/include/assimp/postprocess.h index a0ae0a1bc7..2a74414216 100644 --- a/third_party/libassimp/include/assimp/postprocess.h +++ b/third_party/libassimp/include/assimp/postprocess.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. @@ -438,7 +438,7 @@ enum aiPostProcessSteps aiProcess_FindInstances = 0x100000, // ------------------------------------------------------------------------- - /**
    A postprocessing step to reduce the number of meshes. + /**
    A post-processing step to reduce the number of meshes. * * This will, in fact, reduce the number of draw calls. * @@ -450,7 +450,7 @@ enum aiPostProcessSteps // ------------------------------------------------------------------------- - /**
    A postprocessing step to optimize the scene hierarchy. + /**
    A post-processing step to optimize the scene hierarchy. * * Nodes without animations, bones, lights or cameras assigned are * collapsed and joined. @@ -514,7 +514,7 @@ enum aiPostProcessSteps // ------------------------------------------------------------------------- /**
    This step splits meshes with many bones into sub-meshes so that each - * su-bmesh has fewer or as many bones as a given limit. + * sub-mesh has fewer or as many bones as a given limit. */ aiProcess_SplitByBoneCount = 0x2000000, @@ -541,7 +541,7 @@ enum aiPostProcessSteps * global scaling from your importer settings like in FBX. Use the flag * AI_CONFIG_GLOBAL_SCALE_FACTOR_KEY from the global property table to configure this. * - * Use #AI_CONFIG_GLOBAL_SCALE_FACTOR_KEY to setup the global scaing factor. + * Use #AI_CONFIG_GLOBAL_SCALE_FACTOR_KEY to setup the global scaling factor. */ aiProcess_GlobalScale = 0x8000000, @@ -574,6 +574,11 @@ enum aiPostProcessSteps * This process gives sense back to aiProcess_JoinIdenticalVertices */ aiProcess_DropNormals = 0x40000000, + + // ------------------------------------------------------------------------- + /** + */ + aiProcess_GenBoundingBoxes = 0x80000000 }; diff --git a/third_party/libassimp/include/assimp/qnan.h b/third_party/libassimp/include/assimp/qnan.h index 2516889890..0918bde5e7 100644 --- a/third_party/libassimp/include/assimp/qnan.h +++ b/third_party/libassimp/include/assimp/qnan.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/quaternion.h b/third_party/libassimp/include/assimp/quaternion.h index e2479f2ed8..96574d24b9 100644 --- a/third_party/libassimp/include/assimp/quaternion.h +++ b/third_party/libassimp/include/assimp/quaternion.h @@ -2,7 +2,7 @@ Open Asset Import Library (assimp) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team All rights reserved. diff --git a/third_party/libassimp/include/assimp/quaternion.inl b/third_party/libassimp/include/assimp/quaternion.inl index 0a2c929372..c26648215e 100644 --- a/third_party/libassimp/include/assimp/quaternion.inl +++ b/third_party/libassimp/include/assimp/quaternion.inl @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/scene.h b/third_party/libassimp/include/assimp/scene.h index 867e87de07..2667db85b3 100644 --- a/third_party/libassimp/include/assimp/scene.h +++ b/third_party/libassimp/include/assimp/scene.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -58,6 +58,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "metadata.h" #ifdef __cplusplus +# include extern "C" { #endif @@ -389,6 +390,14 @@ struct aiScene //! Returns an embedded texture const aiTexture* GetEmbeddedTexture(const char* filename) const { + // lookup using texture ID (if referenced like: "*1", "*2", etc.) + if ('*' == *filename) { + int index = std::atoi(filename + 1); + if (0 > index || mNumTextures <= static_cast(index)) + return nullptr; + return mTextures[index]; + } + // lookup using filename const char* shortFilename = GetShortFilename(filename); for (unsigned int i = 0; i < mNumTextures; i++) { const char* shortTextureFilename = GetShortFilename(mTextures[i]->mFilename.C_Str()); diff --git a/third_party/libassimp/include/assimp/texture.h b/third_party/libassimp/include/assimp/texture.h index 5be7229ec4..dc6cbef65c 100644 --- a/third_party/libassimp/include/assimp/texture.h +++ b/third_party/libassimp/include/assimp/texture.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -117,6 +117,8 @@ struct aiTexel #include "./Compiler/poppack1.h" +#define HINTMAXTEXTURELEN 9 + // -------------------------------------------------------------------------------- /** Helper structure to describe an embedded texture * @@ -166,7 +168,7 @@ struct aiTexture { * E.g. 'dds\\0', 'pcx\\0', 'jpg\\0'. All characters are lower-case. * The fourth character will always be '\\0'. */ - char achFormatHint[9];// 8 for string + 1 for terminator. + char achFormatHint[ HINTMAXTEXTURELEN ];// 8 for string + 1 for terminator. /** Data of the texture. * diff --git a/third_party/libassimp/include/assimp/types.h b/third_party/libassimp/include/assimp/types.h index 660479f8a7..8ad5680f39 100644 --- a/third_party/libassimp/include/assimp/types.h +++ b/third_party/libassimp/include/assimp/types.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team @@ -53,6 +53,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include +#include // Our compile configuration #include "defs.h" @@ -65,11 +66,15 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "matrix4x4.h" #include "quaternion.h" +typedef int32_t ai_int32; +typedef uint32_t ai_uint32 ; + #ifdef __cplusplus #include #include // for std::nothrow_t #include // for aiString::Set(const std::string&) + namespace Assimp { //! @cond never namespace Intern { @@ -161,7 +166,14 @@ struct aiColor3D explicit aiColor3D (ai_real _r) : r(_r), g(_r), b(_r) {} aiColor3D (const aiColor3D& o) : r(o.r), g(o.g), b(o.b) {} - /** Component-wise comparison */ + aiColor3D &operator=(const aiColor3D &o) { + r = o.r; + g = o.g; + b = o.b; + return *this; + } + + /** Component-wise comparison */ // TODO: add epsilon? bool operator == (const aiColor3D& other) const {return r == other.r && g == other.g && b == other.b;} @@ -262,8 +274,8 @@ struct aiString } /** Copy constructor */ - aiString(const aiString& rOther) : - length(rOther.length) + aiString(const aiString& rOther) + : length(rOther.length) { // Crop the string to the maximum length length = length>=MAXLEN?MAXLEN-1:length; @@ -273,7 +285,7 @@ struct aiString /** Constructor from std::string */ explicit aiString(const std::string& pString) : - length(pString.length()) + length( (ai_uint32) pString.length()) { length = length>=MAXLEN?MAXLEN-1:length; memcpy( data, pString.c_str(), length); @@ -285,15 +297,15 @@ struct aiString if( pString.length() > MAXLEN - 1) { return; } - length = pString.length(); + length = (ai_uint32)pString.length(); memcpy( data, pString.c_str(), length); data[length] = 0; } /** Copy a const char* to the aiString */ void Set( const char* sz) { - const size_t len = ::strlen(sz); - if( len > MAXLEN - 1) { + const ai_int32 len = (ai_uint32) ::strlen(sz); + if( len > (ai_int32)MAXLEN - 1) { return; } length = len; @@ -339,7 +351,7 @@ struct aiString /** Append a string to the string */ void Append (const char* app) { - const size_t len = ::strlen(app); + const ai_uint32 len = (ai_uint32) ::strlen(app); if (!len) { return; } @@ -372,7 +384,7 @@ struct aiString /** Binary length of the string excluding the terminal 0. This is NOT the * logical length of strings containing UTF-8 multi-byte sequences! It's * the number of bytes from the beginning of the string to its end.*/ - size_t length; + ai_uint32 length; /** String buffer. Size limit is MAXLEN */ char data[MAXLEN]; diff --git a/third_party/libassimp/include/assimp/vector2.h b/third_party/libassimp/include/assimp/vector2.h index 85ca6d0a47..d5ef001542 100644 --- a/third_party/libassimp/include/assimp/vector2.h +++ b/third_party/libassimp/include/assimp/vector2.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/vector2.inl b/third_party/libassimp/include/assimp/vector2.inl index 46c6c9d27f..3b7a7beabb 100644 --- a/third_party/libassimp/include/assimp/vector2.inl +++ b/third_party/libassimp/include/assimp/vector2.inl @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/vector3.h b/third_party/libassimp/include/assimp/vector3.h index 33ae7d22f0..7ff25cf0ad 100644 --- a/third_party/libassimp/include/assimp/vector3.h +++ b/third_party/libassimp/include/assimp/vector3.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/vector3.inl b/third_party/libassimp/include/assimp/vector3.inl index ebe2f82e93..2fce6eddee 100644 --- a/third_party/libassimp/include/assimp/vector3.inl +++ b/third_party/libassimp/include/assimp/vector3.inl @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/include/assimp/version.h b/third_party/libassimp/include/assimp/version.h index 470166edf1..c62a40e118 100644 --- a/third_party/libassimp/include/assimp/version.h +++ b/third_party/libassimp/include/assimp/version.h @@ -3,7 +3,7 @@ Open Asset Import Library (assimp) --------------------------------------------------------------------------- -Copyright (c) 2006-2018, assimp team +Copyright (c) 2006-2019, assimp team diff --git a/third_party/libassimp/packaging/windows-innosetup/script.iss b/third_party/libassimp/packaging/windows-innosetup/script.iss deleted file mode 100644 index 6957406793..0000000000 --- a/third_party/libassimp/packaging/windows-innosetup/script.iss +++ /dev/null @@ -1,103 +0,0 @@ -; Setup script for use with Inno Setup. - -[Setup] -AppName=Open Asset Import Library - SDK -AppVerName=Open Asset Import Library - SDK (v4.1.0) -DefaultDirName={pf}\Assimp -DefaultGroupName=Assimp -UninstallDisplayIcon={app}\bin\x86\assimp.exe -OutputDir=out -AppCopyright=Assimp Development Team -SetupIconFile=..\..\tools\shared\assimp_tools_icon.ico -WizardImageFile=compiler:WizModernImage-IS.BMP -WizardSmallImageFile=compiler:WizModernSmallImage-IS.BMP -LicenseFile=License.rtf -OutputBaseFileName=assimp-sdk-4.1.0-setup -VersionInfoVersion=4.1.0.0 -VersionInfoTextVersion=4.1.0 -VersionInfoCompany=Assimp Development Team -ArchitecturesInstallIn64BitMode=x64 - -[Types] -Name: "full"; Description: "Full installation" -Name: "compact"; Description: "Compact installation, no test models or language bindings" -Name: "custom"; Description: "Custom installation"; Flags: iscustom - -[Components] -Name: "main"; Description: "Main Files (32 and 64 Bit)"; Types: full compact custom; Flags: fixed -Name: "tools"; Description: "Asset Viewer & Command Line Tools (32 and 64 Bit)"; Types: full compact -Name: "help"; Description: "Help Files"; Types: full compact -Name: "samples"; Description: "Samples"; Types: full -Name: "test"; Description: "Test Models (BSD-licensed)"; Types: full -Name: "test_nonbsd"; Description: "Test Models (other (free) licenses)"; Types: full -;Name: "pyassimp"; Description: "Python Bindings"; Types: full -;Name: "dassimp"; Description: "D Bindings"; Types: full -;Name: "assimp_net"; Description: "C#/.NET Bindings"; Types: full - -[Run] -;Filename: "{app}\stub\vc_redist.x86.exe"; Parameters: "/qb"; StatusMsg: "Installing VS2017 redistributable package (32 Bit)"; Check: not IsWin64 -Filename: "{app}\stub\vc_redist.x64.exe"; Parameters: "/qb"; StatusMsg: "Installing VS2017 redistributable package (64 Bit)"; Check: IsWin64 - -[Files] -Source: "readme_installer.txt"; DestDir: "{app}"; Flags: isreadme - -; Installer stub -;Source: "vc_redist.x86.exe"; DestDir: "{app}\stub\"; Check: not IsWin64 -Source: "vc_redist.x64.exe"; DestDir: "{app}\stub\"; Check: IsWin64 - -; Common stuff -Source: "..\..\CREDITS"; DestDir: "{app}" -Source: "..\..\LICENSE"; DestDir: "{app}" -Source: "..\..\README"; DestDir: "{app}" -Source: "WEB"; DestDir: "{app}" - -Source: "..\..\scripts\*"; DestDir: "{app}\scripts"; Flags: recursesubdirs - -; x86 binaries -;Source: "..\..\bin\release\x86\assimp-vc140-mt.dll"; DestDir: "{app}\bin\x86" -;Source: "..\..\bin\release\x86\assimp_viewer.exe"; DestDir: "{app}\bin\x86"; Components: tools -;Source: "C:\Windows\SysWOW64\D3DCompiler_42.dll"; DestDir: "{app}\bin\x86"; Components: tools -;Source: "C:\Windows\SysWOW64\D3DX9_42.dll"; DestDir: "{app}\bin\x86"; Components: tools -;Source: "..\..\bin\release\x86\assimp.exe"; DestDir: "{app}\bin\x86"; Components: tools - -; x64 binaries -Source: "..\..\bin\release\assimp-vc140-mt.dll"; DestDir: "{app}\bin\x64" -Source: "..\..\bin\release\assimp_viewer.exe"; DestDir: "{app}\bin\x64"; Components: tools -Source: "C:\Windows\SysWOW64\D3DCompiler_42.dll"; DestDir: "{app}\bin\x64"; DestName: "D3DCompiler_42.dll"; Components: tools -Source: "C:\Windows\SysWOW64\D3DX9_42.dll"; DestDir: "{app}\bin\x64"; DestName: "D3DX9_42.dll"; Components: tools -Source: "..\..\bin\release\assimp.exe"; DestDir: "{app}\bin\x64"; Components: tools - -; Documentation -;Source: "..\..\doc\AssimpDoc_Html\AssimpDoc.chm"; DestDir: "{app}\doc"; Components: help -;Source: "..\..\doc\AssimpCmdDoc_Html\AssimpCmdDoc.chm"; DestDir: "{app}\doc"; Components: help -;Source: "..\..\doc\datastructure.xml"; DestDir: "{app}\doc"; Components: help - -; Import libraries -;Source: "..\..\lib\release\x86\assimp.lib"; DestDir: "{app}\lib\x86" -Source: "..\..\lib\release\assimp-vc140-mt.lib"; DestDir: "{app}\lib\x64" - -; Samples -Source: "..\..\samples\*"; DestDir: "{app}\samples"; Flags: recursesubdirs; Components: samples - -; Include files -Source: "..\..\include\*"; DestDir: "{app}\include"; Flags: recursesubdirs - -; dAssimp -;Source: "..\..\port\dAssimp\*"; DestDir: "{app}\port\D"; Flags: recursesubdirs; Components: dassimp - -; Assimp.NET -;Source: "..\..\port\Assimp.NET\*"; DestDir: "{app}\port\C#"; Flags: recursesubdirs; Components: assimp_net - -; PyAssimp -;Source: "..\..\port\PyAssimp\*"; DestDir: "{app}\port\Python"; Excludes: "*.pyc,*.dll"; Flags: recursesubdirs; Components: pyassimp - -; Test repository -;Source: "..\..\test\models\*"; DestDir: "{app}\test\models"; Flags: recursesubdirs; Components: test -;Source: "..\..\test\regression\*"; DestDir: "{app}\test\regression"; Flags: recursesubdirs; Components: test -;Source: "..\..\test\models-nonbsd\*"; DestDir: "{app}\test\models-nonbsd"; Flags: recursesubdirs; Components: test_nonbsd - -[Icons] -Name: "{group}\Assimp Manual"; Filename: "{app}\doc\AssimpDoc.chm" ; Components: help -Name: "{group}\Assimp Command Line Manual"; Filename: "{app}\doc\AssimpCmdDoc.chm"; Components: help -Name: "{group}\AssimpView"; Filename: "{app}\bin\x64\assimp_view.exe"; Components: tools; Check: IsWin64 -Name: "{group}\AssimpView"; Filename: "{app}\bin\x86\assimp_view.exe"; Components: tools; Check: not IsWin64 diff --git a/third_party/libassimp/packaging/windows-innosetup/script_x64.iss b/third_party/libassimp/packaging/windows-innosetup/script_x64.iss new file mode 100644 index 0000000000..4d1b67cd0e --- /dev/null +++ b/third_party/libassimp/packaging/windows-innosetup/script_x64.iss @@ -0,0 +1,74 @@ +; Setup script for use with Inno Setup. + +[Setup] +AppName=Open Asset Import Library - SDK +AppVerName=Open Asset Import Library - SDK (v5.0.0) +DefaultDirName={pf}\Assimp +DefaultGroupName=Assimp +UninstallDisplayIcon={app}\bin\x64\assimp.exe +OutputDir=out +AppCopyright=Assimp Development Team +SetupIconFile=..\..\tools\shared\assimp_tools_icon.ico +WizardImageFile=compiler:WizModernImage-IS.BMP +WizardSmallImageFile=compiler:WizModernSmallImage-IS.BMP +LicenseFile=License.rtf +OutputBaseFileName=assimp-sdk-5.0.0-setup +VersionInfoVersion=5.0.0.0 +VersionInfoTextVersion=5.0.0 +VersionInfoCompany=Assimp Development Team +ArchitecturesInstallIn64BitMode=x64 + +[Types] +Name: "full"; Description: "Full installation" +Name: "compact"; Description: "Compact installation, no test models or language bindings" +Name: "custom"; Description: "Custom installation"; Flags: iscustom + +[Components] +Name: "main"; Description: "Main Files ( 64 Bit )"; Types: full compact custom; Flags: fixed +Name: "tools"; Description: "Asset Viewer & Command Line Tools (32 and 64 Bit)"; Types: full compact +Name: "help"; Description: "Help Files"; Types: full compact +Name: "samples"; Description: "Samples"; Types: full +Name: "test"; Description: "Test Models (BSD-licensed)"; Types: full +Name: "test_nonbsd"; Description: "Test Models (other (free) licenses)"; Types: full + +[Run] +Filename: "{app}\stub\vc_redist.x64.exe"; Parameters: "/qb /passive /quiet"; StatusMsg: "Installing VS2017 redistributable package (64 Bit)"; Check: IsWin64 + +[Files] +Source: "readme_installer.txt"; DestDir: "{app}"; Flags: isreadme + +; Installer stub +Source: "vc_redist.x64.exe"; DestDir: "{app}\stub\"; Check: IsWin64 + +; Common stuff +Source: "..\..\CREDITS"; DestDir: "{app}" +Source: "..\..\LICENSE"; DestDir: "{app}" +Source: "..\..\README"; DestDir: "{app}" +Source: "WEB"; DestDir: "{app}" + +Source: "..\..\scripts\*"; DestDir: "{app}\scripts"; Flags: recursesubdirs + +; x64 binaries +Source: "..\..\bin\release\assimp-vc141-mt.dll"; DestDir: "{app}\bin\x64" +Source: "..\..\bin\release\assimp_viewer.exe"; DestDir: "{app}\bin\x64"; Components: tools +Source: "C:\Windows\SysWOW64\D3DCompiler_42.dll"; DestDir: "{app}\bin\x64"; DestName: "D3DCompiler_42.dll"; Components: tools +Source: "C:\Windows\SysWOW64\D3DX9_42.dll"; DestDir: "{app}\bin\x64"; DestName: "D3DX9_42.dll"; Components: tools +Source: "..\..\bin\release\assimp.exe"; DestDir: "{app}\bin\x64"; Components: tools + +; Import libraries +Source: "..\..\lib\release\assimp-vc141-mt.lib"; DestDir: "{app}\lib\x64" + +; Samples +Source: "..\..\samples\*"; DestDir: "{app}\samples"; Flags: recursesubdirs; Components: samples + +; Include files +Source: "..\..\include\*"; DestDir: "{app}\include"; Flags: recursesubdirs + +; CMake files +Source: "..\..\cmake-modules\*"; DestDir: "{app}\cmake-modules"; Flags: recursesubdirs + +[Icons] +; Name: "{group}\Assimp Manual"; Filename: "{app}\doc\AssimpDoc.chm" ; Components: help +; Name: "{group}\Assimp Command Line Manual"; Filename: "{app}\doc\AssimpCmdDoc.chm"; Components: help +; Name: "{group}\AssimpView"; Filename: "{app}\bin\x64\assimp_view.exe"; Components: tools; Check: IsWin64 +; Name: "{group}\AssimpView"; Filename: "{app}\bin\x86\assimp_view.exe"; Components: tools; Check: not IsWin64 diff --git a/third_party/libassimp/packaging/windows-innosetup/script_x86.iss b/third_party/libassimp/packaging/windows-innosetup/script_x86.iss new file mode 100644 index 0000000000..d22d23b648 --- /dev/null +++ b/third_party/libassimp/packaging/windows-innosetup/script_x86.iss @@ -0,0 +1,75 @@ +; Setup script for use with Inno Setup. + +[Setup] +AppName=Open Asset Import Library - SDK +AppVerName=Open Asset Import Library - SDK (v5.0.0) +DefaultDirName={pf}\Assimp +DefaultGroupName=Assimp +UninstallDisplayIcon={app}\bin\x86\assimp.exe +OutputDir=out +AppCopyright=Assimp Development Team +SetupIconFile=..\..\tools\shared\assimp_tools_icon.ico +WizardImageFile=compiler:WizModernImage-IS.BMP +WizardSmallImageFile=compiler:WizModernSmallImage-IS.BMP +LicenseFile=License.rtf +OutputBaseFileName=assimp-sdk-5.0.0-setup +VersionInfoVersion=4.1.0.0 +VersionInfoTextVersion=4.1.0 +VersionInfoCompany=Assimp Development Team +;ArchitecturesInstallIn64BitMode=x64 + +[Types] +Name: "full"; Description: "Full installation" +Name: "compact"; Description: "Compact installation, no test models or language bindings" +Name: "custom"; Description: "Custom installation"; Flags: iscustom + +[Components] +Name: "main"; Description: "Main Files (32 and 64 Bit)"; Types: full compact custom; Flags: fixed +Name: "tools"; Description: "Asset Viewer & Command Line Tools (32 and 64 Bit)"; Types: full compact +Name: "help"; Description: "Help Files"; Types: full compact +Name: "samples"; Description: "Samples"; Types: full +Name: "test"; Description: "Test Models (BSD-licensed)"; Types: full +Name: "test_nonbsd"; Description: "Test Models (other (free) licenses)"; Types: full + +[Run] +Filename: "{app}\stub\vc_redist.x86.exe"; Parameters: "/qb /passive /quiet"; StatusMsg: "Installing VS2017 redistributable package (32 Bit)"; Check: not IsWin64 + +[Files] +Source: "readme_installer.txt"; DestDir: "{app}"; Flags: isreadme + +; Installer stub +Source: "vc_redist.x86.exe"; DestDir: "{app}\stub\"; Check: not IsWin64 + +; Common stuff +Source: "..\..\CREDITS"; DestDir: "{app}" +Source: "..\..\LICENSE"; DestDir: "{app}" +Source: "..\..\README"; DestDir: "{app}" +Source: "WEB"; DestDir: "{app}" + +Source: "..\..\scripts\*"; DestDir: "{app}\scripts"; Flags: recursesubdirs + +; x86 binaries +Source: "..\..\bin\release\assimp-vc141-mt.dll"; DestDir: "{app}\bin\x86" +Source: "..\..\bin\release\assimp_viewer.exe"; DestDir: "{app}\bin\x86"; Components: tools +Source: "C:\Windows\SysWOW64\D3DCompiler_42.dll"; DestDir: "{app}\bin\x86"; Components: tools +Source: "C:\Windows\SysWOW64\D3DX9_42.dll"; DestDir: "{app}\bin\x86"; Components: tools +Source: "..\..\bin\release\assimp.exe"; DestDir: "{app}\bin\x86"; Components: tools + + +; Import libraries +Source: "..\..\lib\release\assimp-vc141-mt.lib"; DestDir: "{app}\lib\x86" + +; Samples +Source: "..\..\samples\*"; DestDir: "{app}\samples"; Flags: recursesubdirs; Components: samples + +; Include files +Source: "..\..\include\*"; DestDir: "{app}\include"; Flags: recursesubdirs + +; CMake files +Source: "..\..\cmake-modules\*"; DestDir: "{app}\cmake-modules"; Flags: recursesubdirs + +[Icons] +; Name: "{group}\Assimp Manual"; Filename: "{app}\doc\AssimpDoc.chm" ; Components: help +; Name: "{group}\Assimp Command Line Manual"; Filename: "{app}\doc\AssimpCmdDoc.chm"; Components: help +; Name: "{group}\AssimpView"; Filename: "{app}\bin\x64\assimp_view.exe"; Components: tools; Check: IsWin64 +; Name: "{group}\AssimpView"; Filename: "{app}\bin\x86\assimp_view.exe"; Components: tools; Check: not IsWin64 diff --git a/third_party/libassimp/port/AndroidJNI/README.md b/third_party/libassimp/port/AndroidJNI/README.md index 570ca4fb34..0b95efd046 100644 --- a/third_party/libassimp/port/AndroidJNI/README.md +++ b/third_party/libassimp/port/AndroidJNI/README.md @@ -1,7 +1,7 @@ Build Asset Importer Lib for Android ==================================== -This module provides a fascade for the io-stream-access to files behind the -android-asset-management within an Android native application. +This module provides a facade for the io-stream-access to files behind the android-asset-management within +an Android-native application. - It is built as a static library - It requires Android NDK with android API > 9 support. @@ -20,6 +20,8 @@ A small example how to wrap assimp for Android: #include Assimp::Importer* importer = new Assimp::Importer(); -Assimp::AndroidJNIIOSystem* ioSystem = new Assimp::AndroidJNIIOSystem(app->activity); -importer->SetIOHandler(ioSystem); +Assimp::AndroidJNIIOSystem *ioSystem = new Assimp::AndroidJNIIOSystem(app->activity); +if ( nullptr != iosSystem ) { + importer->SetIOHandler(ioSystem); +} ``` diff --git a/third_party/libassimp/port/AssimpNET/Readme.md b/third_party/libassimp/port/AssimpNET/Readme.md index bcbfebab17..814cab3e0d 100644 --- a/third_party/libassimp/port/AssimpNET/Readme.md +++ b/third_party/libassimp/port/AssimpNET/Readme.md @@ -1 +1 @@ -Please check the following git-repo for the source: https://bitbucket.org/Starnick/assimpnet +Please check the following git-repo for the source: https://github.com/kebby/assimp-net diff --git a/third_party/libassimp/port/PyAssimp/README.md b/third_party/libassimp/port/PyAssimp/README.md new file mode 100644 index 0000000000..d64d727630 --- /dev/null +++ b/third_party/libassimp/port/PyAssimp/README.md @@ -0,0 +1,91 @@ +PyAssimp Readme +=============== + +A simple Python wrapper for Assimp using `ctypes` to access the library. +Requires Python >= 2.6. + +Python 3 support is mostly here, but not well tested. + +Note that pyassimp is not complete. Many ASSIMP features are missing. + +USAGE +----- + +### Complete example: 3D viewer + +`pyassimp` comes with a simple 3D viewer that shows how to load and display a 3D +model using a shader-based OpenGL pipeline. + +![Screenshot](3d_viewer_screenshot.png) + +To use it, from within `/port/PyAssimp`: + +```console +$ cd scripts +$ python ./3D-viewer +``` + +You can use this code as starting point in your applications. + +### Writing your own code + +To get started with `pyassimp`, examine the simpler `sample.py` script in `scripts/`, +which illustrates the basic usage. All Assimp data structures are wrapped using +`ctypes`. All the data+length fields in Assimp's data structures (such as +`aiMesh::mNumVertices`, `aiMesh::mVertices`) are replaced by simple python +lists, so you can call `len()` on them to get their respective size and access +members using `[]`. + +For example, to load a file named `hello.3ds` and print the first +vertex of the first mesh, you would do (proper error handling +substituted by assertions ...): + +```python + +from pyassimp import * +scene = load('hello.3ds') + +assert len(scene.meshes) +mesh = scene.meshes[0] + +assert len(mesh.vertices) +print(mesh.vertices[0]) + +# don't forget this one, or you will leak! +release(scene) + +``` + +Another example to list the 'top nodes' in a +scene: + +```python + +from pyassimp import * +scene = load('hello.3ds') + +for c in scene.rootnode.children: + print(str(c)) + +release(scene) + +``` + +INSTALL +------- + +Install `pyassimp` by running: + +```console +$ python setup.py install +``` + +PyAssimp requires a assimp dynamic library (`DLL` on windows, +`.so` on linux, `.dynlib` on macOS) in order to work. The default search directories are: + - the current directory + - on linux additionally: `/usr/lib`, `/usr/local/lib`, + `/usr/lib/x86_64-linux-gnu` + +To build that library, refer to the Assimp master `INSTALL` +instructions. To look in more places, edit `./pyassimp/helper.py`. +There's an `additional_dirs` list waiting for your entries. diff --git a/third_party/libassimp/port/PyAssimp/pyassimp/core.py b/third_party/libassimp/port/PyAssimp/pyassimp/core.py index 64dd351a76..c346e26529 100644 --- a/third_party/libassimp/port/PyAssimp/pyassimp/core.py +++ b/third_party/libassimp/port/PyAssimp/pyassimp/core.py @@ -1,550 +1,546 @@ -""" -PyAssimp - -This is the main-module of PyAssimp. -""" - -import sys -if sys.version_info < (2,6): - raise 'pyassimp: need python 2.6 or newer' - -# xrange was renamed range in Python 3 and the original range from Python 2 was removed. -# To keep compatibility with both Python 2 and 3, xrange is set to range for version 3.0 and up. -if sys.version_info >= (3,0): - xrange = range - -import ctypes -import os - -try: import numpy -except: numpy = None - -import logging -logger = logging.getLogger("pyassimp") -# attach default null handler to logger so it doesn't complain -# even if you don't attach another handler to logger -logger.addHandler(logging.NullHandler()) - -from . import structs -from . import helper -from . import postprocess -from .errors import AssimpError -from .formats import available_formats - -class AssimpLib(object): - """ - Assimp-Singleton - """ - load, load_mem, export, export_blob, release, dll = helper.search_library() -_assimp_lib = AssimpLib() - -def make_tuple(ai_obj, type = None): - res = None - - #notes: - # ai_obj._fields_ = [ ("attr", c_type), ... ] - # getattr(ai_obj, e[0]).__class__ == float - - if isinstance(ai_obj, structs.Matrix4x4): - if numpy: - res = numpy.array([getattr(ai_obj, e[0]) for e in ai_obj._fields_]).reshape((4,4)) - #import pdb;pdb.set_trace() - else: - res = [getattr(ai_obj, e[0]) for e in ai_obj._fields_] - res = [res[i:i+4] for i in xrange(0,16,4)] - elif isinstance(ai_obj, structs.Matrix3x3): - if numpy: - res = numpy.array([getattr(ai_obj, e[0]) for e in ai_obj._fields_]).reshape((3,3)) - else: - res = [getattr(ai_obj, e[0]) for e in ai_obj._fields_] - res = [res[i:i+3] for i in xrange(0,9,3)] - else: - if numpy: - res = numpy.array([getattr(ai_obj, e[0]) for e in ai_obj._fields_]) - else: - res = [getattr(ai_obj, e[0]) for e in ai_obj._fields_] - - return res - -# Returns unicode object for Python 2, and str object for Python 3. -def _convert_assimp_string(assimp_string): - try: - return unicode(assimp_string.data, errors='ignore') - except: - return str(assimp_string.data, errors='ignore') - -# It is faster and more correct to have an init function for each assimp class -def _init_face(aiFace): - aiFace.indices = [aiFace.mIndices[i] for i in range(aiFace.mNumIndices)] -assimp_struct_inits = { structs.Face : _init_face } - -def call_init(obj, caller = None): - if helper.hasattr_silent(obj,'contents'): #pointer - _init(obj.contents, obj, caller) - else: - _init(obj,parent=caller) - -def _is_init_type(obj): - if helper.hasattr_silent(obj,'contents'): #pointer - return _is_init_type(obj[0]) - # null-pointer case that arises when we reach a mesh attribute - # like mBitangents which use mNumVertices rather than mNumBitangents - # so it breaks the 'is iterable' check. - # Basically: - # FIXME! - elif not bool(obj): - return False - tname = obj.__class__.__name__ - return not (tname[:2] == 'c_' or tname == 'Structure' \ - or tname == 'POINTER') and not isinstance(obj,int) - -def _init(self, target = None, parent = None): - """ - Custom initialize() for C structs, adds safely accessible member functionality. - - :param target: set the object which receive the added methods. Useful when manipulating - pointers, to skip the intermediate 'contents' deferencing. - """ - if not target: - target = self - - dirself = dir(self) - for m in dirself: - - if m.startswith("_"): - continue - - if m.startswith('mNum'): - if 'm' + m[4:] in dirself: - continue # will be processed later on - else: - name = m[1:].lower() - - obj = getattr(self, m) - setattr(target, name, obj) - continue - - if m == 'mName': - target.name = str(_convert_assimp_string(self.mName)) - target.__class__.__repr__ = lambda x: str(x.__class__) + "(" + getattr(x, 'name','') + ")" - target.__class__.__str__ = lambda x: getattr(x, 'name', '') - continue - - name = m[1:].lower() - - obj = getattr(self, m) - - # Create tuples - if isinstance(obj, structs.assimp_structs_as_tuple): - setattr(target, name, make_tuple(obj)) - logger.debug(str(self) + ": Added array " + str(getattr(target, name)) + " as self." + name.lower()) - continue - - if m.startswith('m'): - - if name == "parent": - setattr(target, name, parent) - logger.debug("Added a parent as self." + name) - continue - - if helper.hasattr_silent(self, 'mNum' + m[1:]): - - length = getattr(self, 'mNum' + m[1:]) - - # -> special case: properties are - # stored as a dict. - if m == 'mProperties': - setattr(target, name, _get_properties(obj, length)) - continue - - - if not length: # empty! - setattr(target, name, []) - logger.debug(str(self) + ": " + name + " is an empty list.") - continue - - - try: - if obj._type_ in structs.assimp_structs_as_tuple: - if numpy: - setattr(target, name, numpy.array([make_tuple(obj[i]) for i in range(length)], dtype=numpy.float32)) - - logger.debug(str(self) + ": Added an array of numpy arrays (type "+ str(type(obj)) + ") as self." + name) - else: - setattr(target, name, [make_tuple(obj[i]) for i in range(length)]) - - logger.debug(str(self) + ": Added a list of lists (type "+ str(type(obj)) + ") as self." + name) - - else: - setattr(target, name, [obj[i] for i in range(length)]) #TODO: maybe not necessary to recreate an array? - - logger.debug(str(self) + ": Added list of " + str(obj) + " " + name + " as self." + name + " (type: " + str(type(obj)) + ")") - - # initialize array elements - try: - init = assimp_struct_inits[type(obj[0])] - except KeyError: - if _is_init_type(obj[0]): - for e in getattr(target, name): - call_init(e, target) - else: - for e in getattr(target, name): - init(e) - - - except IndexError: - logger.error("in " + str(self) +" : mismatch between mNum" + name + " and the actual amount of data in m" + name + ". This may be due to version mismatch between libassimp and pyassimp. Quitting now.") - sys.exit(1) - - except ValueError as e: - - logger.error("In " + str(self) + "->" + name + ": " + str(e) + ". Quitting now.") - if "setting an array element with a sequence" in str(e): - logger.error("Note that pyassimp does not currently " - "support meshes with mixed triangles " - "and quads. Try to load your mesh with" - " a post-processing to triangulate your" - " faces.") - raise e - - - - else: # starts with 'm' but not iterable - setattr(target, name, obj) - logger.debug("Added " + name + " as self." + name + " (type: " + str(type(obj)) + ")") - - if _is_init_type(obj): - call_init(obj, target) - - if isinstance(self, structs.Mesh): - _finalize_mesh(self, target) - - if isinstance(self, structs.Texture): - _finalize_texture(self, target) - - if isinstance(self, structs.Metadata): - _finalize_metadata(self, target) - - - return self - - -def pythonize_assimp(type, obj, scene): - """ This method modify the Assimp data structures - to make them easier to work with in Python. - - Supported operations: - - MESH: replace a list of mesh IDs by reference to these meshes - - ADDTRANSFORMATION: add a reference to an object's transformation taken from their associated node. - - :param type: the type of modification to operate (cf above) - :param obj: the input object to modify - :param scene: a reference to the whole scene - """ - - if type == "MESH": - meshes = [] - for i in obj: - meshes.append(scene.meshes[i]) - return meshes - - if type == "ADDTRANSFORMATION": - def getnode(node, name): - if node.name == name: return node - for child in node.children: - n = getnode(child, name) - if n: return n - - node = getnode(scene.rootnode, obj.name) - if not node: - raise AssimpError("Object " + str(obj) + " has no associated node!") - setattr(obj, "transformation", node.transformation) - -def recur_pythonize(node, scene): - ''' - Recursively call pythonize_assimp on - nodes tree to apply several post-processing to - pythonize the assimp datastructures. - ''' - node.meshes = pythonize_assimp("MESH", node.meshes, scene) - for mesh in node.meshes: - mesh.material = scene.materials[mesh.materialindex] - for cam in scene.cameras: - pythonize_assimp("ADDTRANSFORMATION", cam, scene) - for c in node.children: - recur_pythonize(c, scene) - -def load(filename, - file_type = None, - processing = postprocess.aiProcess_Triangulate): - ''' - Load a model into a scene. On failure throws AssimpError. - - Arguments - --------- - filename: Either a filename or a file object to load model from. - If a file object is passed, file_type MUST be specified - Otherwise Assimp has no idea which importer to use. - This is named 'filename' so as to not break legacy code. - processing: assimp postprocessing parameters. Verbose keywords are imported - from postprocessing, and the parameters can be combined bitwise to - generate the final processing value. Note that the default value will - triangulate quad faces. Example of generating other possible values: - processing = (pyassimp.postprocess.aiProcess_Triangulate | - pyassimp.postprocess.aiProcess_OptimizeMeshes) - file_type: string of file extension, such as 'stl' - - Returns - --------- - Scene object with model data - ''' - - if hasattr(filename, 'read'): - ''' - This is the case where a file object has been passed to load. - It is calling the following function: - const aiScene* aiImportFileFromMemory(const char* pBuffer, - unsigned int pLength, - unsigned int pFlags, - const char* pHint) - ''' - if file_type == None: - raise AssimpError('File type must be specified when passing file objects!') - data = filename.read() - model = _assimp_lib.load_mem(data, - len(data), - processing, - file_type) - else: - # a filename string has been passed - model = _assimp_lib.load(filename.encode(sys.getfilesystemencoding()), processing) - - if not model: - raise AssimpError('Could not import file!') - scene = _init(model.contents) - recur_pythonize(scene.rootnode, scene) - return scene - -def export(scene, - filename, - file_type = None, - processing = postprocess.aiProcess_Triangulate): - ''' - Export a scene. On failure throws AssimpError. - - Arguments - --------- - scene: scene to export. - filename: Filename that the scene should be exported to. - file_type: string of file exporter to use. For example "collada". - processing: assimp postprocessing parameters. Verbose keywords are imported - from postprocessing, and the parameters can be combined bitwise to - generate the final processing value. Note that the default value will - triangulate quad faces. Example of generating other possible values: - processing = (pyassimp.postprocess.aiProcess_Triangulate | - pyassimp.postprocess.aiProcess_OptimizeMeshes) - - ''' - - from ctypes import pointer - exportStatus = _assimp_lib.export(pointer(scene), file_type.encode("ascii"), filename.encode(sys.getfilesystemencoding()), processing) - - if exportStatus != 0: - raise AssimpError('Could not export scene!') - -def export_blob(scene, - file_type = None, - processing = postprocess.aiProcess_Triangulate): - ''' - Export a scene and return a blob in the correct format. On failure throws AssimpError. - - Arguments - --------- - scene: scene to export. - file_type: string of file exporter to use. For example "collada". - processing: assimp postprocessing parameters. Verbose keywords are imported - from postprocessing, and the parameters can be combined bitwise to - generate the final processing value. Note that the default value will - triangulate quad faces. Example of generating other possible values: - processing = (pyassimp.postprocess.aiProcess_Triangulate | - pyassimp.postprocess.aiProcess_OptimizeMeshes) - Returns - --------- - Pointer to structs.ExportDataBlob - ''' - from ctypes import pointer - exportBlobPtr = _assimp_lib.export_blob(pointer(scene), file_type.encode("ascii"), processing) - - if exportBlobPtr == 0: - raise AssimpError('Could not export scene to blob!') - return exportBlobPtr - -def release(scene): - from ctypes import pointer - _assimp_lib.release(pointer(scene)) - -def _finalize_texture(tex, target): - setattr(target, "achformathint", tex.achFormatHint) - if numpy: - data = numpy.array([make_tuple(getattr(tex, "pcData")[i]) for i in range(tex.mWidth * tex.mHeight)]) - else: - data = [make_tuple(getattr(tex, "pcData")[i]) for i in range(tex.mWidth * tex.mHeight)] - setattr(target, "data", data) - -def _finalize_mesh(mesh, target): - """ Building of meshes is a bit specific. - - We override here the various datasets that can - not be process as regular fields. - - For instance, the length of the normals array is - mNumVertices (no mNumNormals is available) - """ - nb_vertices = getattr(mesh, "mNumVertices") - - def fill(name): - mAttr = getattr(mesh, name) - if numpy: - if mAttr: - data = numpy.array([make_tuple(getattr(mesh, name)[i]) for i in range(nb_vertices)], dtype=numpy.float32) - setattr(target, name[1:].lower(), data) - else: - setattr(target, name[1:].lower(), numpy.array([], dtype="float32")) - else: - if mAttr: - data = [make_tuple(getattr(mesh, name)[i]) for i in range(nb_vertices)] - setattr(target, name[1:].lower(), data) - else: - setattr(target, name[1:].lower(), []) - - def fillarray(name): - mAttr = getattr(mesh, name) - - data = [] - for index, mSubAttr in enumerate(mAttr): - if mSubAttr: - data.append([make_tuple(getattr(mesh, name)[index][i]) for i in range(nb_vertices)]) - - if numpy: - setattr(target, name[1:].lower(), numpy.array(data, dtype=numpy.float32)) - else: - setattr(target, name[1:].lower(), data) - - fill("mNormals") - fill("mTangents") - fill("mBitangents") - - fillarray("mColors") - fillarray("mTextureCoords") - - # prepare faces - if numpy: - faces = numpy.array([f.indices for f in target.faces], dtype=numpy.int32) - else: - faces = [f.indices for f in target.faces] - setattr(target, 'faces', faces) - -def _init_metadata_entry(entry): - from ctypes import POINTER, c_bool, c_int32, c_uint64, c_float, c_double, cast - - entry.type = entry.mType - if entry.type == structs.MetadataEntry.AI_BOOL: - entry.data = cast(entry.mData, POINTER(c_bool)).contents.value - elif entry.type == structs.MetadataEntry.AI_INT32: - entry.data = cast(entry.mData, POINTER(c_int32)).contents.value - elif entry.type == structs.MetadataEntry.AI_UINT64: - entry.data = cast(entry.mData, POINTER(c_uint64)).contents.value - elif entry.type == structs.MetadataEntry.AI_FLOAT: - entry.data = cast(entry.mData, POINTER(c_float)).contents.value - elif entry.type == structs.MetadataEntry.AI_DOUBLE: - entry.data = cast(entry.mData, POINTER(c_double)).contents.value - elif entry.type == structs.MetadataEntry.AI_AISTRING: - assimp_string = cast(entry.mData, POINTER(structs.String)).contents - entry.data = _convert_assimp_string(assimp_string) - elif entry.type == structs.MetadataEntry.AI_AIVECTOR3D: - assimp_vector = cast(entry.mData, POINTER(structs.Vector3D)).contents - entry.data = make_tuple(assimp_vector) - - return entry - -def _finalize_metadata(metadata, target): - """ Building the metadata object is a bit specific. - - Firstly, there are two separate arrays: one with metadata keys and one - with metadata values, and there are no corresponding mNum* attributes, - so the C arrays are not converted to Python arrays using the generic - code in the _init function. - - Secondly, a metadata entry value has to be cast according to declared - metadata entry type. - """ - length = metadata.mNumProperties - setattr(target, 'keys', [str(_convert_assimp_string(metadata.mKeys[i])) for i in range(length)]) - setattr(target, 'values', [_init_metadata_entry(metadata.mValues[i]) for i in range(length)]) - -class PropertyGetter(dict): - def __getitem__(self, key): - semantic = 0 - if isinstance(key, tuple): - key, semantic = key - - return dict.__getitem__(self, (key, semantic)) - - def keys(self): - for k in dict.keys(self): - yield k[0] - - def __iter__(self): - return self.keys() - - def items(self): - for k, v in dict.items(self): - yield k[0], v - - -def _get_properties(properties, length): - """ - Convenience Function to get the material properties as a dict - and values in a python format. - """ - result = {} - #read all properties - for p in [properties[i] for i in range(length)]: - #the name - p = p.contents - key = str(_convert_assimp_string(p.mKey)) - key = (key.split('.')[1], p.mSemantic) - - #the data - from ctypes import POINTER, cast, c_int, c_float, sizeof - if p.mType == 1: - arr = cast(p.mData, POINTER(c_float * int(p.mDataLength/sizeof(c_float)) )).contents - value = [x for x in arr] - elif p.mType == 3: #string can't be an array - value = _convert_assimp_string(cast(p.mData, POINTER(structs.MaterialPropertyString)).contents) - - elif p.mType == 4: - arr = cast(p.mData, POINTER(c_int * int(p.mDataLength/sizeof(c_int)) )).contents - value = [x for x in arr] - else: - value = p.mData[:p.mDataLength] - - if len(value) == 1: - [value] = value - - result[key] = value - - return PropertyGetter(result) - -def decompose_matrix(matrix): - if not isinstance(matrix, structs.Matrix4x4): - raise AssimpError("pyassimp.decompose_matrix failed: Not a Matrix4x4!") - - scaling = structs.Vector3D() - rotation = structs.Quaternion() - position = structs.Vector3D() - - from ctypes import byref, pointer - _assimp_lib.dll.aiDecomposeMatrix(pointer(matrix), byref(scaling), byref(rotation), byref(position)) - return scaling._init(), rotation._init(), position._init() - +""" +PyAssimp + +This is the main-module of PyAssimp. +""" + +import sys +if sys.version_info < (2,6): + raise RuntimeError('pyassimp: need python 2.6 or newer') + +# xrange was renamed range in Python 3 and the original range from Python 2 was removed. +# To keep compatibility with both Python 2 and 3, xrange is set to range for version 3.0 and up. +if sys.version_info >= (3,0): + xrange = range + + +try: import numpy +except ImportError: numpy = None +import logging +import ctypes +logger = logging.getLogger("pyassimp") +# attach default null handler to logger so it doesn't complain +# even if you don't attach another handler to logger +logger.addHandler(logging.NullHandler()) + +from . import structs +from . import helper +from . import postprocess +from .errors import AssimpError + +class AssimpLib(object): + """ + Assimp-Singleton + """ + load, load_mem, export, export_blob, release, dll = helper.search_library() +_assimp_lib = AssimpLib() + +def make_tuple(ai_obj, type = None): + res = None + + #notes: + # ai_obj._fields_ = [ ("attr", c_type), ... ] + # getattr(ai_obj, e[0]).__class__ == float + + if isinstance(ai_obj, structs.Matrix4x4): + if numpy: + res = numpy.array([getattr(ai_obj, e[0]) for e in ai_obj._fields_]).reshape((4,4)) + #import pdb;pdb.set_trace() + else: + res = [getattr(ai_obj, e[0]) for e in ai_obj._fields_] + res = [res[i:i+4] for i in xrange(0,16,4)] + elif isinstance(ai_obj, structs.Matrix3x3): + if numpy: + res = numpy.array([getattr(ai_obj, e[0]) for e in ai_obj._fields_]).reshape((3,3)) + else: + res = [getattr(ai_obj, e[0]) for e in ai_obj._fields_] + res = [res[i:i+3] for i in xrange(0,9,3)] + else: + if numpy: + res = numpy.array([getattr(ai_obj, e[0]) for e in ai_obj._fields_]) + else: + res = [getattr(ai_obj, e[0]) for e in ai_obj._fields_] + + return res + +# Returns unicode object for Python 2, and str object for Python 3. +def _convert_assimp_string(assimp_string): + if sys.version_info >= (3, 0): + return str(assimp_string.data, errors='ignore') + else: + return unicode(assimp_string.data, errors='ignore') + +# It is faster and more correct to have an init function for each assimp class +def _init_face(aiFace): + aiFace.indices = [aiFace.mIndices[i] for i in range(aiFace.mNumIndices)] +assimp_struct_inits = { structs.Face : _init_face } + +def call_init(obj, caller = None): + if helper.hasattr_silent(obj,'contents'): #pointer + _init(obj.contents, obj, caller) + else: + _init(obj,parent=caller) + +def _is_init_type(obj): + + if obj and helper.hasattr_silent(obj,'contents'): #pointer + return _is_init_type(obj[0]) + # null-pointer case that arises when we reach a mesh attribute + # like mBitangents which use mNumVertices rather than mNumBitangents + # so it breaks the 'is iterable' check. + # Basically: + # FIXME! + elif not bool(obj): + return False + tname = obj.__class__.__name__ + return not (tname[:2] == 'c_' or tname == 'Structure' \ + or tname == 'POINTER') and not isinstance(obj, (int, str, bytes)) + +def _init(self, target = None, parent = None): + """ + Custom initialize() for C structs, adds safely accessible member functionality. + + :param target: set the object which receive the added methods. Useful when manipulating + pointers, to skip the intermediate 'contents' deferencing. + """ + if not target: + target = self + + dirself = dir(self) + for m in dirself: + + if m.startswith("_"): + continue + + if m.startswith('mNum'): + if 'm' + m[4:] in dirself: + continue # will be processed later on + else: + name = m[1:].lower() + + obj = getattr(self, m) + setattr(target, name, obj) + continue + + if m == 'mName': + target.name = str(_convert_assimp_string(self.mName)) + target.__class__.__repr__ = lambda x: str(x.__class__) + "(" + getattr(x, 'name','') + ")" + target.__class__.__str__ = lambda x: getattr(x, 'name', '') + continue + + name = m[1:].lower() + + obj = getattr(self, m) + + # Create tuples + if isinstance(obj, structs.assimp_structs_as_tuple): + setattr(target, name, make_tuple(obj)) + logger.debug(str(self) + ": Added array " + str(getattr(target, name)) + " as self." + name.lower()) + continue + + if m.startswith('m'): + + if name == "parent": + setattr(target, name, parent) + logger.debug("Added a parent as self." + name) + continue + + if helper.hasattr_silent(self, 'mNum' + m[1:]): + + length = getattr(self, 'mNum' + m[1:]) + + # -> special case: properties are + # stored as a dict. + if m == 'mProperties': + setattr(target, name, _get_properties(obj, length)) + continue + + + if not length: # empty! + setattr(target, name, []) + logger.debug(str(self) + ": " + name + " is an empty list.") + continue + + + try: + if obj._type_ in structs.assimp_structs_as_tuple: + if numpy: + setattr(target, name, numpy.array([make_tuple(obj[i]) for i in range(length)], dtype=numpy.float32)) + + logger.debug(str(self) + ": Added an array of numpy arrays (type "+ str(type(obj)) + ") as self." + name) + else: + setattr(target, name, [make_tuple(obj[i]) for i in range(length)]) + + logger.debug(str(self) + ": Added a list of lists (type "+ str(type(obj)) + ") as self." + name) + + else: + setattr(target, name, [obj[i] for i in range(length)]) #TODO: maybe not necessary to recreate an array? + + logger.debug(str(self) + ": Added list of " + str(obj) + " " + name + " as self." + name + " (type: " + str(type(obj)) + ")") + + # initialize array elements + try: + init = assimp_struct_inits[type(obj[0])] + except KeyError: + if _is_init_type(obj[0]): + for e in getattr(target, name): + call_init(e, target) + else: + for e in getattr(target, name): + init(e) + + + except IndexError: + logger.error("in " + str(self) +" : mismatch between mNum" + name + " and the actual amount of data in m" + name + ". This may be due to version mismatch between libassimp and pyassimp. Quitting now.") + sys.exit(1) + + except ValueError as e: + + logger.error("In " + str(self) + "->" + name + ": " + str(e) + ". Quitting now.") + if "setting an array element with a sequence" in str(e): + logger.error("Note that pyassimp does not currently " + "support meshes with mixed triangles " + "and quads. Try to load your mesh with" + " a post-processing to triangulate your" + " faces.") + raise e + + + + else: # starts with 'm' but not iterable + setattr(target, name, obj) + logger.debug("Added " + name + " as self." + name + " (type: " + str(type(obj)) + ")") + + if _is_init_type(obj): + call_init(obj, target) + + if isinstance(self, structs.Mesh): + _finalize_mesh(self, target) + + if isinstance(self, structs.Texture): + _finalize_texture(self, target) + + if isinstance(self, structs.Metadata): + _finalize_metadata(self, target) + + + return self + + +def pythonize_assimp(type, obj, scene): + """ This method modify the Assimp data structures + to make them easier to work with in Python. + + Supported operations: + - MESH: replace a list of mesh IDs by reference to these meshes + - ADDTRANSFORMATION: add a reference to an object's transformation taken from their associated node. + + :param type: the type of modification to operate (cf above) + :param obj: the input object to modify + :param scene: a reference to the whole scene + """ + + if type == "MESH": + meshes = [] + for i in obj: + meshes.append(scene.meshes[i]) + return meshes + + if type == "ADDTRANSFORMATION": + def getnode(node, name): + if node.name == name: return node + for child in node.children: + n = getnode(child, name) + if n: return n + + node = getnode(scene.rootnode, obj.name) + if not node: + raise AssimpError("Object " + str(obj) + " has no associated node!") + setattr(obj, "transformation", node.transformation) + +def recur_pythonize(node, scene): + ''' + Recursively call pythonize_assimp on + nodes tree to apply several post-processing to + pythonize the assimp datastructures. + ''' + node.meshes = pythonize_assimp("MESH", node.meshes, scene) + for mesh in node.meshes: + mesh.material = scene.materials[mesh.materialindex] + for cam in scene.cameras: + pythonize_assimp("ADDTRANSFORMATION", cam, scene) + for c in node.children: + recur_pythonize(c, scene) + +def load(filename, + file_type = None, + processing = postprocess.aiProcess_Triangulate): + ''' + Load a model into a scene. On failure throws AssimpError. + + Arguments + --------- + filename: Either a filename or a file object to load model from. + If a file object is passed, file_type MUST be specified + Otherwise Assimp has no idea which importer to use. + This is named 'filename' so as to not break legacy code. + processing: assimp postprocessing parameters. Verbose keywords are imported + from postprocessing, and the parameters can be combined bitwise to + generate the final processing value. Note that the default value will + triangulate quad faces. Example of generating other possible values: + processing = (pyassimp.postprocess.aiProcess_Triangulate | + pyassimp.postprocess.aiProcess_OptimizeMeshes) + file_type: string of file extension, such as 'stl' + + Returns + --------- + Scene object with model data + ''' + + if hasattr(filename, 'read'): + # This is the case where a file object has been passed to load. + # It is calling the following function: + # const aiScene* aiImportFileFromMemory(const char* pBuffer, + # unsigned int pLength, + # unsigned int pFlags, + # const char* pHint) + if file_type is None: + raise AssimpError('File type must be specified when passing file objects!') + data = filename.read() + model = _assimp_lib.load_mem(data, + len(data), + processing, + file_type) + else: + # a filename string has been passed + model = _assimp_lib.load(filename.encode(sys.getfilesystemencoding()), processing) + + if not model: + raise AssimpError('Could not import file!') + scene = _init(model.contents) + recur_pythonize(scene.rootnode, scene) + return scene + +def export(scene, + filename, + file_type = None, + processing = postprocess.aiProcess_Triangulate): + ''' + Export a scene. On failure throws AssimpError. + + Arguments + --------- + scene: scene to export. + filename: Filename that the scene should be exported to. + file_type: string of file exporter to use. For example "collada". + processing: assimp postprocessing parameters. Verbose keywords are imported + from postprocessing, and the parameters can be combined bitwise to + generate the final processing value. Note that the default value will + triangulate quad faces. Example of generating other possible values: + processing = (pyassimp.postprocess.aiProcess_Triangulate | + pyassimp.postprocess.aiProcess_OptimizeMeshes) + + ''' + + exportStatus = _assimp_lib.export(ctypes.pointer(scene), file_type.encode("ascii"), filename.encode(sys.getfilesystemencoding()), processing) + + if exportStatus != 0: + raise AssimpError('Could not export scene!') + +def export_blob(scene, + file_type = None, + processing = postprocess.aiProcess_Triangulate): + ''' + Export a scene and return a blob in the correct format. On failure throws AssimpError. + + Arguments + --------- + scene: scene to export. + file_type: string of file exporter to use. For example "collada". + processing: assimp postprocessing parameters. Verbose keywords are imported + from postprocessing, and the parameters can be combined bitwise to + generate the final processing value. Note that the default value will + triangulate quad faces. Example of generating other possible values: + processing = (pyassimp.postprocess.aiProcess_Triangulate | + pyassimp.postprocess.aiProcess_OptimizeMeshes) + Returns + --------- + Pointer to structs.ExportDataBlob + ''' + exportBlobPtr = _assimp_lib.export_blob(ctypes.pointer(scene), file_type.encode("ascii"), processing) + + if exportBlobPtr == 0: + raise AssimpError('Could not export scene to blob!') + return exportBlobPtr + +def release(scene): + _assimp_lib.release(ctypes.pointer(scene)) + +def _finalize_texture(tex, target): + setattr(target, "achformathint", tex.achFormatHint) + if numpy: + data = numpy.array([make_tuple(getattr(tex, "pcData")[i]) for i in range(tex.mWidth * tex.mHeight)]) + else: + data = [make_tuple(getattr(tex, "pcData")[i]) for i in range(tex.mWidth * tex.mHeight)] + setattr(target, "data", data) + +def _finalize_mesh(mesh, target): + """ Building of meshes is a bit specific. + + We override here the various datasets that can + not be process as regular fields. + + For instance, the length of the normals array is + mNumVertices (no mNumNormals is available) + """ + nb_vertices = getattr(mesh, "mNumVertices") + + def fill(name): + mAttr = getattr(mesh, name) + if numpy: + if mAttr: + data = numpy.array([make_tuple(getattr(mesh, name)[i]) for i in range(nb_vertices)], dtype=numpy.float32) + setattr(target, name[1:].lower(), data) + else: + setattr(target, name[1:].lower(), numpy.array([], dtype="float32")) + else: + if mAttr: + data = [make_tuple(getattr(mesh, name)[i]) for i in range(nb_vertices)] + setattr(target, name[1:].lower(), data) + else: + setattr(target, name[1:].lower(), []) + + def fillarray(name): + mAttr = getattr(mesh, name) + + data = [] + for index, mSubAttr in enumerate(mAttr): + if mSubAttr: + data.append([make_tuple(getattr(mesh, name)[index][i]) for i in range(nb_vertices)]) + + if numpy: + setattr(target, name[1:].lower(), numpy.array(data, dtype=numpy.float32)) + else: + setattr(target, name[1:].lower(), data) + + fill("mNormals") + fill("mTangents") + fill("mBitangents") + + fillarray("mColors") + fillarray("mTextureCoords") + + # prepare faces + if numpy: + faces = numpy.array([f.indices for f in target.faces], dtype=numpy.int32) + else: + faces = [f.indices for f in target.faces] + setattr(target, 'faces', faces) + +def _init_metadata_entry(entry): + entry.type = entry.mType + if entry.type == structs.MetadataEntry.AI_BOOL: + entry.data = ctypes.cast(entry.mData, ctypes.POINTER(ctypes.c_bool)).contents.value + elif entry.type == structs.MetadataEntry.AI_INT32: + entry.data = ctypes.cast(entry.mData, ctypes.POINTER(ctypes.c_int32)).contents.value + elif entry.type == structs.MetadataEntry.AI_UINT64: + entry.data = ctypes.cast(entry.mData, ctypes.POINTER(ctypes.c_uint64)).contents.value + elif entry.type == structs.MetadataEntry.AI_FLOAT: + entry.data = ctypes.cast(entry.mData, ctypes.POINTER(ctypes.c_float)).contents.value + elif entry.type == structs.MetadataEntry.AI_DOUBLE: + entry.data = ctypes.cast(entry.mData, ctypes.POINTER(ctypes.c_double)).contents.value + elif entry.type == structs.MetadataEntry.AI_AISTRING: + assimp_string = ctypes.cast(entry.mData, ctypes.POINTER(structs.String)).contents + entry.data = _convert_assimp_string(assimp_string) + elif entry.type == structs.MetadataEntry.AI_AIVECTOR3D: + assimp_vector = ctypes.cast(entry.mData, ctypes.POINTER(structs.Vector3D)).contents + entry.data = make_tuple(assimp_vector) + + return entry + +def _finalize_metadata(metadata, target): + """ Building the metadata object is a bit specific. + + Firstly, there are two separate arrays: one with metadata keys and one + with metadata values, and there are no corresponding mNum* attributes, + so the C arrays are not converted to Python arrays using the generic + code in the _init function. + + Secondly, a metadata entry value has to be cast according to declared + metadata entry type. + """ + length = metadata.mNumProperties + setattr(target, 'keys', [str(_convert_assimp_string(metadata.mKeys[i])) for i in range(length)]) + setattr(target, 'values', [_init_metadata_entry(metadata.mValues[i]) for i in range(length)]) + +class PropertyGetter(dict): + def __getitem__(self, key): + semantic = 0 + if isinstance(key, tuple): + key, semantic = key + + return dict.__getitem__(self, (key, semantic)) + + def keys(self): + for k in dict.keys(self): + yield k[0] + + def __iter__(self): + return self.keys() + + def items(self): + for k, v in dict.items(self): + yield k[0], v + + +def _get_properties(properties, length): + """ + Convenience Function to get the material properties as a dict + and values in a python format. + """ + result = {} + #read all properties + for p in [properties[i] for i in range(length)]: + #the name + p = p.contents + key = str(_convert_assimp_string(p.mKey)) + key = (key.split('.')[1], p.mSemantic) + + #the data + if p.mType == 1: + arr = ctypes.cast(p.mData, + ctypes.POINTER(ctypes.c_float * int(p.mDataLength/ctypes.sizeof(ctypes.c_float))) + ).contents + value = [x for x in arr] + elif p.mType == 3: #string can't be an array + value = _convert_assimp_string(ctypes.cast(p.mData, ctypes.POINTER(structs.MaterialPropertyString)).contents) + + elif p.mType == 4: + arr = ctypes.cast(p.mData, + ctypes.POINTER(ctypes.c_int * int(p.mDataLength/ctypes.sizeof(ctypes.c_int))) + ).contents + value = [x for x in arr] + else: + value = p.mData[:p.mDataLength] + + if len(value) == 1: + [value] = value + + result[key] = value + + return PropertyGetter(result) + +def decompose_matrix(matrix): + if not isinstance(matrix, structs.Matrix4x4): + raise AssimpError("pyassimp.decompose_matrix failed: Not a Matrix4x4!") + + scaling = structs.Vector3D() + rotation = structs.Quaternion() + position = structs.Vector3D() + + _assimp_lib.dll.aiDecomposeMatrix(ctypes.pointer(matrix), + ctypes.byref(scaling), + ctypes.byref(rotation), + ctypes.byref(position)) + return scaling._init(), rotation._init(), position._init() + diff --git a/third_party/libassimp/port/PyAssimp/pyassimp/formats.py b/third_party/libassimp/port/PyAssimp/pyassimp/formats.py index baba1645cc..5d454e5b71 100644 --- a/third_party/libassimp/port/PyAssimp/pyassimp/formats.py +++ b/third_party/libassimp/port/PyAssimp/pyassimp/formats.py @@ -21,7 +21,7 @@ FORMATS = ["CSM", "STL", "IRR", "Q3O", - "Q3D" + "Q3D", "MS3D", "Q3S", "ZGL", diff --git a/third_party/libassimp/port/PyAssimp/pyassimp/helper.py b/third_party/libassimp/port/PyAssimp/pyassimp/helper.py index 4e9f10e948..5c1aca8270 100644 --- a/third_party/libassimp/port/PyAssimp/pyassimp/helper.py +++ b/third_party/libassimp/port/PyAssimp/pyassimp/helper.py @@ -1,280 +1,281 @@ -#-*- coding: UTF-8 -*- - -""" -Some fancy helper functions. -""" - -import os -import ctypes -from ctypes import POINTER -import operator - -from distutils.sysconfig import get_python_lib -import re -import sys - -try: import numpy -except: numpy = None - -import logging;logger = logging.getLogger("pyassimp") - -from .errors import AssimpError - -additional_dirs, ext_whitelist = [],[] - -# populate search directories and lists of allowed file extensions -# depending on the platform we're running on. -if os.name=='posix': - additional_dirs.append('./') - additional_dirs.append('/usr/lib/') - additional_dirs.append('/usr/lib/x86_64-linux-gnu/') - additional_dirs.append('/usr/local/lib/') - - if 'LD_LIBRARY_PATH' in os.environ: - additional_dirs.extend([item for item in os.environ['LD_LIBRARY_PATH'].split(':') if item]) - - # check if running from anaconda. - if "conda" or "continuum" in sys.version.lower(): - cur_path = get_python_lib() - pattern = re.compile('.*\/lib\/') - conda_lib = pattern.match(cur_path).group() - logger.info("Adding Anaconda lib path:"+ conda_lib) - additional_dirs.append(conda_lib) - - # note - this won't catch libassimp.so.N.n, but - # currently there's always a symlink called - # libassimp.so in /usr/local/lib. - ext_whitelist.append('.so') - # libassimp.dylib in /usr/local/lib - ext_whitelist.append('.dylib') - -elif os.name=='nt': - ext_whitelist.append('.dll') - path_dirs = os.environ['PATH'].split(';') - additional_dirs.extend(path_dirs) - -def vec2tuple(x): - """ Converts a VECTOR3D to a Tuple """ - return (x.x, x.y, x.z) - -def transform(vector3, matrix4x4): - """ Apply a transformation matrix on a 3D vector. - - :param vector3: array with 3 elements - :param matrix4x4: 4x4 matrix - """ - if numpy: - return numpy.dot(matrix4x4, numpy.append(vector3, 1.)) - else: - m0,m1,m2,m3 = matrix4x4; x,y,z = vector3 - return [ - m0[0]*x + m0[1]*y + m0[2]*z + m0[3], - m1[0]*x + m1[1]*y + m1[2]*z + m1[3], - m2[0]*x + m2[1]*y + m2[2]*z + m2[3], - m3[0]*x + m3[1]*y + m3[2]*z + m3[3] - ] - -def _inv(matrix4x4): - m0,m1,m2,m3 = matrix4x4 - - det = m0[3]*m1[2]*m2[1]*m3[0] - m0[2]*m1[3]*m2[1]*m3[0] - \ - m0[3]*m1[1]*m2[2]*m3[0] + m0[1]*m1[3]*m2[2]*m3[0] + \ - m0[2]*m1[1]*m2[3]*m3[0] - m0[1]*m1[2]*m2[3]*m3[0] - \ - m0[3]*m1[2]*m2[0]*m3[1] + m0[2]*m1[3]*m2[0]*m3[1] + \ - m0[3]*m1[0]*m2[2]*m3[1] - m0[0]*m1[3]*m2[2]*m3[1] - \ - m0[2]*m1[0]*m2[3]*m3[1] + m0[0]*m1[2]*m2[3]*m3[1] + \ - m0[3]*m1[1]*m2[0]*m3[2] - m0[1]*m1[3]*m2[0]*m3[2] - \ - m0[3]*m1[0]*m2[1]*m3[2] + m0[0]*m1[3]*m2[1]*m3[2] + \ - m0[1]*m1[0]*m2[3]*m3[2] - m0[0]*m1[1]*m2[3]*m3[2] - \ - m0[2]*m1[1]*m2[0]*m3[3] + m0[1]*m1[2]*m2[0]*m3[3] + \ - m0[2]*m1[0]*m2[1]*m3[3] - m0[0]*m1[2]*m2[1]*m3[3] - \ - m0[1]*m1[0]*m2[2]*m3[3] + m0[0]*m1[1]*m2[2]*m3[3] - - return[[( m1[2]*m2[3]*m3[1] - m1[3]*m2[2]*m3[1] + m1[3]*m2[1]*m3[2] - m1[1]*m2[3]*m3[2] - m1[2]*m2[1]*m3[3] + m1[1]*m2[2]*m3[3]) /det, - ( m0[3]*m2[2]*m3[1] - m0[2]*m2[3]*m3[1] - m0[3]*m2[1]*m3[2] + m0[1]*m2[3]*m3[2] + m0[2]*m2[1]*m3[3] - m0[1]*m2[2]*m3[3]) /det, - ( m0[2]*m1[3]*m3[1] - m0[3]*m1[2]*m3[1] + m0[3]*m1[1]*m3[2] - m0[1]*m1[3]*m3[2] - m0[2]*m1[1]*m3[3] + m0[1]*m1[2]*m3[3]) /det, - ( m0[3]*m1[2]*m2[1] - m0[2]*m1[3]*m2[1] - m0[3]*m1[1]*m2[2] + m0[1]*m1[3]*m2[2] + m0[2]*m1[1]*m2[3] - m0[1]*m1[2]*m2[3]) /det], - [( m1[3]*m2[2]*m3[0] - m1[2]*m2[3]*m3[0] - m1[3]*m2[0]*m3[2] + m1[0]*m2[3]*m3[2] + m1[2]*m2[0]*m3[3] - m1[0]*m2[2]*m3[3]) /det, - ( m0[2]*m2[3]*m3[0] - m0[3]*m2[2]*m3[0] + m0[3]*m2[0]*m3[2] - m0[0]*m2[3]*m3[2] - m0[2]*m2[0]*m3[3] + m0[0]*m2[2]*m3[3]) /det, - ( m0[3]*m1[2]*m3[0] - m0[2]*m1[3]*m3[0] - m0[3]*m1[0]*m3[2] + m0[0]*m1[3]*m3[2] + m0[2]*m1[0]*m3[3] - m0[0]*m1[2]*m3[3]) /det, - ( m0[2]*m1[3]*m2[0] - m0[3]*m1[2]*m2[0] + m0[3]*m1[0]*m2[2] - m0[0]*m1[3]*m2[2] - m0[2]*m1[0]*m2[3] + m0[0]*m1[2]*m2[3]) /det], - [( m1[1]*m2[3]*m3[0] - m1[3]*m2[1]*m3[0] + m1[3]*m2[0]*m3[1] - m1[0]*m2[3]*m3[1] - m1[1]*m2[0]*m3[3] + m1[0]*m2[1]*m3[3]) /det, - ( m0[3]*m2[1]*m3[0] - m0[1]*m2[3]*m3[0] - m0[3]*m2[0]*m3[1] + m0[0]*m2[3]*m3[1] + m0[1]*m2[0]*m3[3] - m0[0]*m2[1]*m3[3]) /det, - ( m0[1]*m1[3]*m3[0] - m0[3]*m1[1]*m3[0] + m0[3]*m1[0]*m3[1] - m0[0]*m1[3]*m3[1] - m0[1]*m1[0]*m3[3] + m0[0]*m1[1]*m3[3]) /det, - ( m0[3]*m1[1]*m2[0] - m0[1]*m1[3]*m2[0] - m0[3]*m1[0]*m2[1] + m0[0]*m1[3]*m2[1] + m0[1]*m1[0]*m2[3] - m0[0]*m1[1]*m2[3]) /det], - [( m1[2]*m2[1]*m3[0] - m1[1]*m2[2]*m3[0] - m1[2]*m2[0]*m3[1] + m1[0]*m2[2]*m3[1] + m1[1]*m2[0]*m3[2] - m1[0]*m2[1]*m3[2]) /det, - ( m0[1]*m2[2]*m3[0] - m0[2]*m2[1]*m3[0] + m0[2]*m2[0]*m3[1] - m0[0]*m2[2]*m3[1] - m0[1]*m2[0]*m3[2] + m0[0]*m2[1]*m3[2]) /det, - ( m0[2]*m1[1]*m3[0] - m0[1]*m1[2]*m3[0] - m0[2]*m1[0]*m3[1] + m0[0]*m1[2]*m3[1] + m0[1]*m1[0]*m3[2] - m0[0]*m1[1]*m3[2]) /det, - ( m0[1]*m1[2]*m2[0] - m0[2]*m1[1]*m2[0] + m0[2]*m1[0]*m2[1] - m0[0]*m1[2]*m2[1] - m0[1]*m1[0]*m2[2] + m0[0]*m1[1]*m2[2]) /det]] - -def get_bounding_box(scene): - bb_min = [1e10, 1e10, 1e10] # x,y,z - bb_max = [-1e10, -1e10, -1e10] # x,y,z - inv = numpy.linalg.inv if numpy else _inv - return get_bounding_box_for_node(scene.rootnode, bb_min, bb_max, inv(scene.rootnode.transformation)) - -def get_bounding_box_for_node(node, bb_min, bb_max, transformation): - - if numpy: - transformation = numpy.dot(transformation, node.transformation) - else: - t0,t1,t2,t3 = transformation - T0,T1,T2,T3 = node.transformation - transformation = [ [ - t0[0]*T0[0] + t0[1]*T1[0] + t0[2]*T2[0] + t0[3]*T3[0], - t0[0]*T0[1] + t0[1]*T1[1] + t0[2]*T2[1] + t0[3]*T3[1], - t0[0]*T0[2] + t0[1]*T1[2] + t0[2]*T2[2] + t0[3]*T3[2], - t0[0]*T0[3] + t0[1]*T1[3] + t0[2]*T2[3] + t0[3]*T3[3] - ],[ - t1[0]*T0[0] + t1[1]*T1[0] + t1[2]*T2[0] + t1[3]*T3[0], - t1[0]*T0[1] + t1[1]*T1[1] + t1[2]*T2[1] + t1[3]*T3[1], - t1[0]*T0[2] + t1[1]*T1[2] + t1[2]*T2[2] + t1[3]*T3[2], - t1[0]*T0[3] + t1[1]*T1[3] + t1[2]*T2[3] + t1[3]*T3[3] - ],[ - t2[0]*T0[0] + t2[1]*T1[0] + t2[2]*T2[0] + t2[3]*T3[0], - t2[0]*T0[1] + t2[1]*T1[1] + t2[2]*T2[1] + t2[3]*T3[1], - t2[0]*T0[2] + t2[1]*T1[2] + t2[2]*T2[2] + t2[3]*T3[2], - t2[0]*T0[3] + t2[1]*T1[3] + t2[2]*T2[3] + t2[3]*T3[3] - ],[ - t3[0]*T0[0] + t3[1]*T1[0] + t3[2]*T2[0] + t3[3]*T3[0], - t3[0]*T0[1] + t3[1]*T1[1] + t3[2]*T2[1] + t3[3]*T3[1], - t3[0]*T0[2] + t3[1]*T1[2] + t3[2]*T2[2] + t3[3]*T3[2], - t3[0]*T0[3] + t3[1]*T1[3] + t3[2]*T2[3] + t3[3]*T3[3] - ] ] - - for mesh in node.meshes: - for v in mesh.vertices: - v = transform(v, transformation) - bb_min[0] = min(bb_min[0], v[0]) - bb_min[1] = min(bb_min[1], v[1]) - bb_min[2] = min(bb_min[2], v[2]) - bb_max[0] = max(bb_max[0], v[0]) - bb_max[1] = max(bb_max[1], v[1]) - bb_max[2] = max(bb_max[2], v[2]) - - - for child in node.children: - bb_min, bb_max = get_bounding_box_for_node(child, bb_min, bb_max, transformation) - - return bb_min, bb_max - -def try_load_functions(library_path, dll): - ''' - Try to bind to aiImportFile and aiReleaseImport - - Arguments - --------- - library_path: path to current lib - dll: ctypes handle to library - - Returns - --------- - If unsuccessful: - None - If successful: - Tuple containing (library_path, - load from filename function, - load from memory function, - export to filename function, - export to blob function, - release function, - ctypes handle to assimp library) - ''' - - try: - load = dll.aiImportFile - release = dll.aiReleaseImport - load_mem = dll.aiImportFileFromMemory - export = dll.aiExportScene - export2blob = dll.aiExportSceneToBlob - except AttributeError: - #OK, this is a library, but it doesn't have the functions we need - return None - - # library found! - from .structs import Scene, ExportDataBlob - load.restype = POINTER(Scene) - load_mem.restype = POINTER(Scene) - export2blob.restype = POINTER(ExportDataBlob) - return (library_path, load, load_mem, export, export2blob, release, dll) - -def search_library(): - ''' - Loads the assimp library. - Throws exception AssimpError if no library_path is found - - Returns: tuple, (load from filename function, - load from memory function, - export to filename function, - export to blob function, - release function, - dll) - ''' - #this path - folder = os.path.dirname(__file__) - - # silence 'DLL not found' message boxes on win - try: - ctypes.windll.kernel32.SetErrorMode(0x8007) - except AttributeError: - pass - - candidates = [] - # test every file - for curfolder in [folder]+additional_dirs: - if os.path.isdir(curfolder): - for filename in os.listdir(curfolder): - # our minimum requirement for candidates is that - # they should contain 'assimp' somewhere in - # their name - if filename.lower().find('assimp')==-1 : - continue - is_out=1 - for et in ext_whitelist: - if et in filename.lower(): - is_out=0 - break - if is_out: - continue - - library_path = os.path.join(curfolder, filename) - logger.debug('Try ' + library_path) - try: - dll = ctypes.cdll.LoadLibrary(library_path) - except Exception as e: - logger.warning(str(e)) - # OK, this except is evil. But different OSs will throw different - # errors. So just ignore any errors. - continue - # see if the functions we need are in the dll - loaded = try_load_functions(library_path, dll) - if loaded: candidates.append(loaded) - - if not candidates: - # no library found - raise AssimpError("assimp library not found") - else: - # get the newest library_path - candidates = map(lambda x: (os.lstat(x[0])[-2], x), candidates) - res = max(candidates, key=operator.itemgetter(0))[1] - logger.debug('Using assimp library located at ' + res[0]) - - # XXX: if there are 1000 dll/so files containing 'assimp' - # in their name, do we have all of them in our address - # space now until gc kicks in? - - # XXX: take version postfix of the .so on linux? - return res[1:] - -def hasattr_silent(object, name): - """ - Calls hasttr() with the given parameters and preserves the legacy (pre-Python 3.2) - functionality of silently catching exceptions. - - Returns the result of hasatter() or False if an exception was raised. - """ - - try: - return hasattr(object, name) - except: - return False +#-*- coding: UTF-8 -*- + +""" +Some fancy helper functions. +""" + +import os +import ctypes +import operator + +from distutils.sysconfig import get_python_lib +import re +import sys + +try: import numpy +except ImportError: numpy = None + +import logging;logger = logging.getLogger("pyassimp") + +from .errors import AssimpError + +additional_dirs, ext_whitelist = [],[] + +# populate search directories and lists of allowed file extensions +# depending on the platform we're running on. +if os.name=='posix': + additional_dirs.append('./') + additional_dirs.append('/usr/lib/') + additional_dirs.append('/usr/lib/x86_64-linux-gnu/') + additional_dirs.append('/usr/local/lib/') + + if 'LD_LIBRARY_PATH' in os.environ: + additional_dirs.extend([item for item in os.environ['LD_LIBRARY_PATH'].split(':') if item]) + + # check if running from anaconda. + if "conda" or "continuum" in sys.version.lower(): + cur_path = get_python_lib() + pattern = re.compile('.*\/lib\/') + conda_lib = pattern.match(cur_path).group() + logger.info("Adding Anaconda lib path:"+ conda_lib) + additional_dirs.append(conda_lib) + + # note - this won't catch libassimp.so.N.n, but + # currently there's always a symlink called + # libassimp.so in /usr/local/lib. + ext_whitelist.append('.so') + # libassimp.dylib in /usr/local/lib + ext_whitelist.append('.dylib') + +elif os.name=='nt': + ext_whitelist.append('.dll') + path_dirs = os.environ['PATH'].split(';') + additional_dirs.extend(path_dirs) + +def vec2tuple(x): + """ Converts a VECTOR3D to a Tuple """ + return (x.x, x.y, x.z) + +def transform(vector3, matrix4x4): + """ Apply a transformation matrix on a 3D vector. + + :param vector3: array with 3 elements + :param matrix4x4: 4x4 matrix + """ + if numpy: + return numpy.dot(matrix4x4, numpy.append(vector3, 1.)) + else: + m0,m1,m2,m3 = matrix4x4; x,y,z = vector3 + return [ + m0[0]*x + m0[1]*y + m0[2]*z + m0[3], + m1[0]*x + m1[1]*y + m1[2]*z + m1[3], + m2[0]*x + m2[1]*y + m2[2]*z + m2[3], + m3[0]*x + m3[1]*y + m3[2]*z + m3[3] + ] + +def _inv(matrix4x4): + m0,m1,m2,m3 = matrix4x4 + + det = m0[3]*m1[2]*m2[1]*m3[0] - m0[2]*m1[3]*m2[1]*m3[0] - \ + m0[3]*m1[1]*m2[2]*m3[0] + m0[1]*m1[3]*m2[2]*m3[0] + \ + m0[2]*m1[1]*m2[3]*m3[0] - m0[1]*m1[2]*m2[3]*m3[0] - \ + m0[3]*m1[2]*m2[0]*m3[1] + m0[2]*m1[3]*m2[0]*m3[1] + \ + m0[3]*m1[0]*m2[2]*m3[1] - m0[0]*m1[3]*m2[2]*m3[1] - \ + m0[2]*m1[0]*m2[3]*m3[1] + m0[0]*m1[2]*m2[3]*m3[1] + \ + m0[3]*m1[1]*m2[0]*m3[2] - m0[1]*m1[3]*m2[0]*m3[2] - \ + m0[3]*m1[0]*m2[1]*m3[2] + m0[0]*m1[3]*m2[1]*m3[2] + \ + m0[1]*m1[0]*m2[3]*m3[2] - m0[0]*m1[1]*m2[3]*m3[2] - \ + m0[2]*m1[1]*m2[0]*m3[3] + m0[1]*m1[2]*m2[0]*m3[3] + \ + m0[2]*m1[0]*m2[1]*m3[3] - m0[0]*m1[2]*m2[1]*m3[3] - \ + m0[1]*m1[0]*m2[2]*m3[3] + m0[0]*m1[1]*m2[2]*m3[3] + + return[[( m1[2]*m2[3]*m3[1] - m1[3]*m2[2]*m3[1] + m1[3]*m2[1]*m3[2] - m1[1]*m2[3]*m3[2] - m1[2]*m2[1]*m3[3] + m1[1]*m2[2]*m3[3]) /det, + ( m0[3]*m2[2]*m3[1] - m0[2]*m2[3]*m3[1] - m0[3]*m2[1]*m3[2] + m0[1]*m2[3]*m3[2] + m0[2]*m2[1]*m3[3] - m0[1]*m2[2]*m3[3]) /det, + ( m0[2]*m1[3]*m3[1] - m0[3]*m1[2]*m3[1] + m0[3]*m1[1]*m3[2] - m0[1]*m1[3]*m3[2] - m0[2]*m1[1]*m3[3] + m0[1]*m1[2]*m3[3]) /det, + ( m0[3]*m1[2]*m2[1] - m0[2]*m1[3]*m2[1] - m0[3]*m1[1]*m2[2] + m0[1]*m1[3]*m2[2] + m0[2]*m1[1]*m2[3] - m0[1]*m1[2]*m2[3]) /det], + [( m1[3]*m2[2]*m3[0] - m1[2]*m2[3]*m3[0] - m1[3]*m2[0]*m3[2] + m1[0]*m2[3]*m3[2] + m1[2]*m2[0]*m3[3] - m1[0]*m2[2]*m3[3]) /det, + ( m0[2]*m2[3]*m3[0] - m0[3]*m2[2]*m3[0] + m0[3]*m2[0]*m3[2] - m0[0]*m2[3]*m3[2] - m0[2]*m2[0]*m3[3] + m0[0]*m2[2]*m3[3]) /det, + ( m0[3]*m1[2]*m3[0] - m0[2]*m1[3]*m3[0] - m0[3]*m1[0]*m3[2] + m0[0]*m1[3]*m3[2] + m0[2]*m1[0]*m3[3] - m0[0]*m1[2]*m3[3]) /det, + ( m0[2]*m1[3]*m2[0] - m0[3]*m1[2]*m2[0] + m0[3]*m1[0]*m2[2] - m0[0]*m1[3]*m2[2] - m0[2]*m1[0]*m2[3] + m0[0]*m1[2]*m2[3]) /det], + [( m1[1]*m2[3]*m3[0] - m1[3]*m2[1]*m3[0] + m1[3]*m2[0]*m3[1] - m1[0]*m2[3]*m3[1] - m1[1]*m2[0]*m3[3] + m1[0]*m2[1]*m3[3]) /det, + ( m0[3]*m2[1]*m3[0] - m0[1]*m2[3]*m3[0] - m0[3]*m2[0]*m3[1] + m0[0]*m2[3]*m3[1] + m0[1]*m2[0]*m3[3] - m0[0]*m2[1]*m3[3]) /det, + ( m0[1]*m1[3]*m3[0] - m0[3]*m1[1]*m3[0] + m0[3]*m1[0]*m3[1] - m0[0]*m1[3]*m3[1] - m0[1]*m1[0]*m3[3] + m0[0]*m1[1]*m3[3]) /det, + ( m0[3]*m1[1]*m2[0] - m0[1]*m1[3]*m2[0] - m0[3]*m1[0]*m2[1] + m0[0]*m1[3]*m2[1] + m0[1]*m1[0]*m2[3] - m0[0]*m1[1]*m2[3]) /det], + [( m1[2]*m2[1]*m3[0] - m1[1]*m2[2]*m3[0] - m1[2]*m2[0]*m3[1] + m1[0]*m2[2]*m3[1] + m1[1]*m2[0]*m3[2] - m1[0]*m2[1]*m3[2]) /det, + ( m0[1]*m2[2]*m3[0] - m0[2]*m2[1]*m3[0] + m0[2]*m2[0]*m3[1] - m0[0]*m2[2]*m3[1] - m0[1]*m2[0]*m3[2] + m0[0]*m2[1]*m3[2]) /det, + ( m0[2]*m1[1]*m3[0] - m0[1]*m1[2]*m3[0] - m0[2]*m1[0]*m3[1] + m0[0]*m1[2]*m3[1] + m0[1]*m1[0]*m3[2] - m0[0]*m1[1]*m3[2]) /det, + ( m0[1]*m1[2]*m2[0] - m0[2]*m1[1]*m2[0] + m0[2]*m1[0]*m2[1] - m0[0]*m1[2]*m2[1] - m0[1]*m1[0]*m2[2] + m0[0]*m1[1]*m2[2]) /det]] + +def get_bounding_box(scene): + bb_min = [1e10, 1e10, 1e10] # x,y,z + bb_max = [-1e10, -1e10, -1e10] # x,y,z + inv = numpy.linalg.inv if numpy else _inv + return get_bounding_box_for_node(scene.rootnode, bb_min, bb_max, inv(scene.rootnode.transformation)) + +def get_bounding_box_for_node(node, bb_min, bb_max, transformation): + + if numpy: + transformation = numpy.dot(transformation, node.transformation) + else: + t0,t1,t2,t3 = transformation + T0,T1,T2,T3 = node.transformation + transformation = [ [ + t0[0]*T0[0] + t0[1]*T1[0] + t0[2]*T2[0] + t0[3]*T3[0], + t0[0]*T0[1] + t0[1]*T1[1] + t0[2]*T2[1] + t0[3]*T3[1], + t0[0]*T0[2] + t0[1]*T1[2] + t0[2]*T2[2] + t0[3]*T3[2], + t0[0]*T0[3] + t0[1]*T1[3] + t0[2]*T2[3] + t0[3]*T3[3] + ],[ + t1[0]*T0[0] + t1[1]*T1[0] + t1[2]*T2[0] + t1[3]*T3[0], + t1[0]*T0[1] + t1[1]*T1[1] + t1[2]*T2[1] + t1[3]*T3[1], + t1[0]*T0[2] + t1[1]*T1[2] + t1[2]*T2[2] + t1[3]*T3[2], + t1[0]*T0[3] + t1[1]*T1[3] + t1[2]*T2[3] + t1[3]*T3[3] + ],[ + t2[0]*T0[0] + t2[1]*T1[0] + t2[2]*T2[0] + t2[3]*T3[0], + t2[0]*T0[1] + t2[1]*T1[1] + t2[2]*T2[1] + t2[3]*T3[1], + t2[0]*T0[2] + t2[1]*T1[2] + t2[2]*T2[2] + t2[3]*T3[2], + t2[0]*T0[3] + t2[1]*T1[3] + t2[2]*T2[3] + t2[3]*T3[3] + ],[ + t3[0]*T0[0] + t3[1]*T1[0] + t3[2]*T2[0] + t3[3]*T3[0], + t3[0]*T0[1] + t3[1]*T1[1] + t3[2]*T2[1] + t3[3]*T3[1], + t3[0]*T0[2] + t3[1]*T1[2] + t3[2]*T2[2] + t3[3]*T3[2], + t3[0]*T0[3] + t3[1]*T1[3] + t3[2]*T2[3] + t3[3]*T3[3] + ] ] + + for mesh in node.meshes: + for v in mesh.vertices: + v = transform(v, transformation) + bb_min[0] = min(bb_min[0], v[0]) + bb_min[1] = min(bb_min[1], v[1]) + bb_min[2] = min(bb_min[2], v[2]) + bb_max[0] = max(bb_max[0], v[0]) + bb_max[1] = max(bb_max[1], v[1]) + bb_max[2] = max(bb_max[2], v[2]) + + + for child in node.children: + bb_min, bb_max = get_bounding_box_for_node(child, bb_min, bb_max, transformation) + + return bb_min, bb_max + +def try_load_functions(library_path, dll): + ''' + Try to bind to aiImportFile and aiReleaseImport + + Arguments + --------- + library_path: path to current lib + dll: ctypes handle to library + + Returns + --------- + If unsuccessful: + None + If successful: + Tuple containing (library_path, + load from filename function, + load from memory function, + export to filename function, + export to blob function, + release function, + ctypes handle to assimp library) + ''' + + try: + load = dll.aiImportFile + release = dll.aiReleaseImport + load_mem = dll.aiImportFileFromMemory + export = dll.aiExportScene + export2blob = dll.aiExportSceneToBlob + except AttributeError: + #OK, this is a library, but it doesn't have the functions we need + return None + + # library found! + from .structs import Scene, ExportDataBlob + load.restype = ctypes.POINTER(Scene) + load_mem.restype = ctypes.POINTER(Scene) + export2blob.restype = ctypes.POINTER(ExportDataBlob) + return (library_path, load, load_mem, export, export2blob, release, dll) + +def search_library(): + ''' + Loads the assimp library. + Throws exception AssimpError if no library_path is found + + Returns: tuple, (load from filename function, + load from memory function, + export to filename function, + export to blob function, + release function, + dll) + ''' + #this path + folder = os.path.dirname(__file__) + + # silence 'DLL not found' message boxes on win + try: + ctypes.windll.kernel32.SetErrorMode(0x8007) + except AttributeError: + pass + + candidates = [] + # test every file + for curfolder in [folder]+additional_dirs: + if os.path.isdir(curfolder): + for filename in os.listdir(curfolder): + # our minimum requirement for candidates is that + # they should contain 'assimp' somewhere in + # their name + if filename.lower().find('assimp')==-1 : + continue + is_out=1 + for et in ext_whitelist: + if et in filename.lower(): + is_out=0 + break + if is_out: + continue + + library_path = os.path.join(curfolder, filename) + logger.debug('Try ' + library_path) + try: + dll = ctypes.cdll.LoadLibrary(library_path) + except Exception as e: + logger.warning(str(e)) + # OK, this except is evil. But different OSs will throw different + # errors. So just ignore any errors. + continue + # see if the functions we need are in the dll + loaded = try_load_functions(library_path, dll) + if loaded: candidates.append(loaded) + + if not candidates: + # no library found + raise AssimpError("assimp library not found") + else: + # get the newest library_path + candidates = map(lambda x: (os.lstat(x[0])[-2], x), candidates) + res = max(candidates, key=operator.itemgetter(0))[1] + logger.debug('Using assimp library located at ' + res[0]) + + # XXX: if there are 1000 dll/so files containing 'assimp' + # in their name, do we have all of them in our address + # space now until gc kicks in? + + # XXX: take version postfix of the .so on linux? + return res[1:] + +def hasattr_silent(object, name): + """ + Calls hasttr() with the given parameters and preserves the legacy (pre-Python 3.2) + functionality of silently catching exceptions. + + Returns the result of hasatter() or False if an exception was raised. + """ + + try: + if not object: + return False + return hasattr(object, name) + except AttributeError: + return False diff --git a/third_party/libassimp/port/PyAssimp/pyassimp/postprocess.py b/third_party/libassimp/port/PyAssimp/pyassimp/postprocess.py index 932c7c660b..0c55d6798d 100644 --- a/third_party/libassimp/port/PyAssimp/pyassimp/postprocess.py +++ b/third_party/libassimp/port/PyAssimp/pyassimp/postprocess.py @@ -435,6 +435,7 @@ aiProcess_Debone = 0x4000000 aiProcess_GenEntityMeshes = 0x100000 aiProcess_OptimizeAnimations = 0x200000 aiProcess_FixTexturePaths = 0x200000 +aiProcess_EmbedTextures = 0x10000000, ## @def aiProcess_ConvertToLeftHanded # @brief Shortcut flag for Direct3D-based applications. diff --git a/third_party/libassimp/port/PyAssimp/pyassimp/structs.py b/third_party/libassimp/port/PyAssimp/pyassimp/structs.py index ddfd87f8a9..d478b861bb 100644 --- a/third_party/libassimp/port/PyAssimp/pyassimp/structs.py +++ b/third_party/libassimp/port/PyAssimp/pyassimp/structs.py @@ -1,6 +1,6 @@ #-*- coding: UTF-8 -*- -from ctypes import POINTER, c_void_p, c_int, c_uint, c_char, c_float, Structure, c_char_p, c_double, c_ubyte, c_size_t, c_uint32 +from ctypes import POINTER, c_void_p, c_uint, c_char, c_float, Structure, c_char_p, c_double, c_ubyte, c_size_t, c_uint32 class Vector2D(Structure): @@ -70,7 +70,7 @@ class String(Structure): See 'types.h' for details. """ - MAXLEN = 1024 + MAXLEN = 1024 _fields_ = [ # Binary length of the string excluding the terminal 0. This is NOT the diff --git a/third_party/libassimp/port/PyAssimp/scripts/3d_viewer_py3.py b/third_party/libassimp/port/PyAssimp/scripts/3d_viewer_py3.py index 4c88edc7b6..fcee637178 100755 --- a/third_party/libassimp/port/PyAssimp/scripts/3d_viewer_py3.py +++ b/third_party/libassimp/port/PyAssimp/scripts/3d_viewer_py3.py @@ -468,7 +468,7 @@ class PyAssimp3DViewer: try: self.set_shaders_v130() self.prepare_shaders() - except RuntimeError, message: + except RuntimeError as message: sys.stderr.write("%s\n" % message) sys.stdout.write("Could not compile shaders in version 1.30, trying version 1.20\n") @@ -1177,6 +1177,22 @@ class PyAssimp3DViewer: return True def controls_3d(self, dx, dy, zooming_one_shot=False): + """ Orbiting the camera is implemented the following way: + + - the rotation is split into a rotation around the *world* Z axis + (controlled by the horizontal mouse motion along X) and a + rotation around the *X* axis of the camera (pitch) *shifted to + the focal origin* (the world origin for now). This is controlled + by the vertical motion of the mouse (Y axis). + - as a result, the resulting transformation of the camera in the + world frame C' is: + C' = (T · Rx · T⁻¹ · (Rz · C)⁻¹)⁻¹ + where: + - C is the original camera transformation in the world frame, + - Rz is the rotation along the Z axis (in the world frame) + - T is the translation camera -> world (ie, the inverse of the + translation part of C + - Rx is the rotation around X in the (translated) camera frame """ CAMERA_TRANSLATION_FACTOR = 0.01 CAMERA_ROTATION_FACTOR = 0.01 @@ -1188,26 +1204,6 @@ class PyAssimp3DViewer: distance = numpy.linalg.norm(self.focal_point - current_pos) if self.is_rotating: - """ Orbiting the camera is implemented the following way: - - - the rotation is split into a rotation around the *world* Z axis - (controlled by the horizontal mouse motion along X) and a - rotation around the *X* axis of the camera (pitch) *shifted to - the focal origin* (the world origin for now). This is controlled - by the vertical motion of the mouse (Y axis). - - - as a result, the resulting transformation of the camera in the - world frame C' is: - C' = (T · Rx · T⁻¹ · (Rz · C)⁻¹)⁻¹ - - where: - - C is the original camera transformation in the world frame, - - Rz is the rotation along the Z axis (in the world frame) - - T is the translation camera -> world (ie, the inverse of the - translation part of C - - Rx is the rotation around X in the (translated) camera frame - """ - rotation_camera_x = dy * CAMERA_ROTATION_FACTOR rotation_world_z = dx * CAMERA_ROTATION_FACTOR world_z_rotation = transformations.euler_matrix(0, 0, rotation_world_z) diff --git a/third_party/libassimp/port/PyAssimp/scripts/fixed_pipeline_3d_viewer.py b/third_party/libassimp/port/PyAssimp/scripts/fixed_pipeline_3d_viewer.py index 7f98b90049..c2f6cebb7c 100755 --- a/third_party/libassimp/port/PyAssimp/scripts/fixed_pipeline_3d_viewer.py +++ b/third_party/libassimp/port/PyAssimp/scripts/fixed_pipeline_3d_viewer.py @@ -24,12 +24,13 @@ This sample is based on several sources, including: - ASSIMP's C++ SimpleOpenGL viewer """ -import os, sys +import sys from OpenGL.GLUT import * from OpenGL.GLU import * from OpenGL.GL import * -import logging;logger = logging.getLogger("pyassimp_opengl") +import logging +logger = logging.getLogger("pyassimp_opengl") logging.basicConfig(level=logging.INFO) import math diff --git a/third_party/libassimp/port/PyAssimp/scripts/sample.py b/third_party/libassimp/port/PyAssimp/scripts/sample.py index 9012eb3740..3cd4b3ec43 100755 --- a/third_party/libassimp/port/PyAssimp/scripts/sample.py +++ b/third_party/libassimp/port/PyAssimp/scripts/sample.py @@ -5,7 +5,7 @@ This module demonstrates the functionality of PyAssimp. """ -import os, sys +import sys import logging logging.basicConfig(level=logging.INFO) @@ -50,8 +50,8 @@ def main(filename=None): print(" colors:" + str(len(mesh.colors))) tcs = mesh.texturecoords if tcs.any(): - for index, tc in enumerate(tcs): - print(" texture-coords "+ str(index) + ":" + str(len(tcs[index])) + "first3:" + str(tcs[index][:3])) + for tc_index, tc in enumerate(tcs): + print(" texture-coords "+ str(tc_index) + ":" + str(len(tcs[tc_index])) + "first3:" + str(tcs[tc_index][:3])) else: print(" no texture coordinates") diff --git a/third_party/libassimp/port/PyAssimp/setup.py b/third_party/libassimp/port/PyAssimp/setup.py index e19e497f08..a3497d6578 100644 --- a/third_party/libassimp/port/PyAssimp/setup.py +++ b/third_party/libassimp/port/PyAssimp/setup.py @@ -8,7 +8,7 @@ def readme(): return f.read() setup(name='pyassimp', - version='4.1.3', + version='4.1.4', license='ISC', description='Python bindings for the Open Asset Import Library (ASSIMP)', long_description=readme(), diff --git a/third_party/libassimp/port/iOS/IPHONEOS_ARM64E_TOOLCHAIN.cmake b/third_party/libassimp/port/iOS/IPHONEOS_ARM64E_TOOLCHAIN.cmake new file mode 100644 index 0000000000..0cf2b6b66e --- /dev/null +++ b/third_party/libassimp/port/iOS/IPHONEOS_ARM64E_TOOLCHAIN.cmake @@ -0,0 +1,17 @@ +INCLUDE(CMakeForceCompiler) + +SET (CMAKE_CROSSCOMPILING TRUE) +SET (CMAKE_SYSTEM_NAME "Darwin") +SET (CMAKE_SYSTEM_PROCESSOR "arm64e") +SET (IOS TRUE) + +SET (IOS_SDK_DEVICE iPhoneOS) + +SET (SDKVER "${IOS_SDK_VERSION}") +SET (DEVROOT "${XCODE_ROOT_DIR}/Platforms/${IOS_SDK_DEVICE}.platform/Developer") + + +SET (CMAKE_FIND_ROOT_PATH "${SDKROOT}" "${DEVROOT}") +SET (CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +SET (CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +SET (CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) \ No newline at end of file diff --git a/third_party/libassimp/port/iOS/build.sh b/third_party/libassimp/port/iOS/build.sh index 288c9c4a43..f118c45c16 100755 --- a/third_party/libassimp/port/iOS/build.sh +++ b/third_party/libassimp/port/iOS/build.sh @@ -31,7 +31,7 @@ TOOLCHAIN=$XCODE_ROOT_DIR/Toolchains/XcodeDefault.xctoolchain CMAKE_C_COMPILER=$(xcrun -find cc) CMAKE_CXX_COMPILER=$(xcrun -find c++) -BUILD_ARCHS_DEVICE="arm64 armv7s armv7" +BUILD_ARCHS_DEVICE="arm64e arm64 armv7s armv7" BUILD_ARCHS_SIMULATOR="x86_64 i386" BUILD_ARCHS_ALL=($BUILD_ARCHS_DEVICE $BUILD_ARCHS_SIMULATOR) diff --git a/third_party/libassimp/port/jassimp/jassimp-native/src/jassimp.cpp b/third_party/libassimp/port/jassimp/jassimp-native/src/jassimp.cpp index 070dbc95d4..0cf01b1e35 100644 --- a/third_party/libassimp/port/jassimp/jassimp-native/src/jassimp.cpp +++ b/third_party/libassimp/port/jassimp/jassimp-native/src/jassimp.cpp @@ -1,6 +1,7 @@ #include "jassimp.h" #include +#include #include #include #include @@ -248,7 +249,7 @@ static bool call(JNIEnv *env, jobject object, const char* typeName, const char* return false; } - jboolean jReturnValue = env->CallBooleanMethod(object, mid, params[0].l); + jboolean jReturnValue = env->CallBooleanMethodA(object, mid, params); return (bool)jReturnValue; } @@ -591,6 +592,24 @@ class JavaIOSystem : public Assimp::IOSystem { }; +class JavaProgressHandler : public Assimp::ProgressHandler { + private: + JNIEnv* mJniEnv; + jobject& mJavaProgressHandler; + + public: + JavaProgressHandler(JNIEnv* env, jobject& javaProgressHandler) : + mJniEnv(env), + mJavaProgressHandler(javaProgressHandler) + {}; + + bool Update(float percentage) + { + jvalue params[1]; + params[0].f = percentage; + return call(mJniEnv, mJavaProgressHandler, "jassimp/AiProgressHandler", "update", "(F)Z", params); + } +}; static bool loadMeshes(JNIEnv *env, const aiScene* cScene, jobject& jScene) { @@ -1880,7 +1899,7 @@ JNIEXPORT jstring JNICALL Java_jassimp_Jassimp_getErrorString JNIEXPORT jobject JNICALL Java_jassimp_Jassimp_aiImportFile - (JNIEnv *env, jclass jClazz, jstring jFilename, jlong postProcess, jobject ioSystem) + (JNIEnv *env, jclass jClazz, jstring jFilename, jlong postProcess, jobject ioSystem, jobject progressHandler) { jobject jScene = NULL; @@ -1896,6 +1915,11 @@ JNIEXPORT jobject JNICALL Java_jassimp_Jassimp_aiImportFile lprintf("Created aiFileIO\n"); } + if(progressHandler != NULL) + { + imp.SetProgressHandler(new JavaProgressHandler(env, progressHandler)); + } + lprintf("opening file: %s\n", cFilename); /* do import */ diff --git a/third_party/libassimp/port/jassimp/jassimp-native/src/jassimp.h b/third_party/libassimp/port/jassimp/jassimp-native/src/jassimp.h index 7d4b66e29c..2a4a845381 100644 --- a/third_party/libassimp/port/jassimp/jassimp-native/src/jassimp.h +++ b/third_party/libassimp/port/jassimp/jassimp-native/src/jassimp.h @@ -39,7 +39,7 @@ JNIEXPORT jstring JNICALL Java_jassimp_Jassimp_getErrorString * Signature: (Ljava/lang/String;J)Ljassimp/AiScene; */ JNIEXPORT jobject JNICALL Java_jassimp_Jassimp_aiImportFile - (JNIEnv *, jclass, jstring, jlong, jobject); + (JNIEnv *, jclass, jstring, jlong, jobject, jobject); #ifdef __cplusplus } diff --git a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiAnimation.java b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiAnimation.java index fca3bc53de..777d2a9fe6 100644 --- a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiAnimation.java +++ b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiAnimation.java @@ -54,6 +54,26 @@ import java.util.List; * {@link AiMesh} for a description and comparison of these APIs. */ public final class AiAnimation { + /** + * Name. + */ + private final String m_name; + + /** + * Duration. + */ + private final double m_duration; + + /** + * Ticks per second. + */ + private final double m_ticksPerSecond; + + /** + * Bone animation channels. + */ + private final List m_nodeAnims = new ArrayList(); + /** * Constructor. * @@ -151,29 +171,5 @@ public final class AiAnimation { */ public List getMeshChannels() { throw new UnsupportedOperationException("not implemented yet"); - } - - - /** - * Name. - */ - private final String m_name; - - - /** - * Duration. - */ - private final double m_duration; - - - /** - * Ticks per second. - */ - private final double m_ticksPerSecond; - - - /** - * Bone animation channels. - */ - private final List m_nodeAnims = new ArrayList(); + } } \ No newline at end of file diff --git a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiBone.java b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiBone.java index 87c4b8199a..1e6d49beba 100644 --- a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiBone.java +++ b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiBone.java @@ -55,6 +55,24 @@ import java.util.List; * writable and may be modified. */ public final class AiBone { + /** + * Name of the bone. + */ + private String m_name; + + + /** + * Bone weights. + */ + private final List m_boneWeights = + new ArrayList(); + + + /** + * Offset matrix. + */ + private Object m_offsetMatrix; + /** * Constructor. */ @@ -114,24 +132,5 @@ public final class AiBone { AiWrapperProvider wrapperProvider) { return (M4) m_offsetMatrix; - } - - - /** - * Name of the bone. - */ - private String m_name; - - - /** - * Bone weights. - */ - private final List m_boneWeights = - new ArrayList(); - - - /** - * Offset matrix. - */ - private Object m_offsetMatrix; + } } diff --git a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiClassLoaderIOSystem.java b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiClassLoaderIOSystem.java index e14a87f771..95afc2e02a 100644 --- a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiClassLoaderIOSystem.java +++ b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiClassLoaderIOSystem.java @@ -139,10 +139,8 @@ public class AiClassLoaderIOSystem implements AiIOSystem { return false; } - else - { - return true; - } + + return true; } diff --git a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiColor.java b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiColor.java index 25eb251d60..6befeecbd5 100644 --- a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiColor.java +++ b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiColor.java @@ -50,6 +50,16 @@ import java.nio.ByteBuffer; * modify the underlying mesh. */ public final class AiColor { + /** + * Wrapped buffer. + */ + private final ByteBuffer m_buffer; + + /** + * Offset into m_buffer. + */ + private final int m_offset; + /** * Constructor. * @@ -147,16 +157,4 @@ public final class AiColor { return "[" + getRed() + ", " + getGreen() + ", " + getBlue() + ", " + getAlpha() + "]"; } - - - /** - * Wrapped buffer. - */ - private final ByteBuffer m_buffer; - - - /** - * Offset into m_buffer. - */ - private final int m_offset; } diff --git a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiMaterial.java b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiMaterial.java index 7a9abc0d3c..8582d881a4 100644 --- a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiMaterial.java +++ b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiMaterial.java @@ -70,6 +70,17 @@ import java.util.Set; * properties (i.e., properties starting with TEX_). */ public final class AiMaterial { + /** + * List of properties. + */ + private final List m_properties = new ArrayList(); + + /** + * Number of textures for each type. + */ + private final Map m_numTextures = + new EnumMap(AiTextureType.class); + /** * Enumerates all supported material properties. */ @@ -317,7 +328,36 @@ public final class AiMaterial { * properties easily. */ public static final class Property { + /** + * Key. + */ + private final String m_key; + + /** + * Semantic. + */ + private final int m_semantic; + + + /** + * Index. + */ + private final int m_index; + + + /** + * Type. + */ + private final PropertyType m_type; + + + /** + * Data. + */ + private final Object m_data; + + /** * Constructor. * * @param key @@ -417,39 +457,9 @@ public final class AiMaterial { * * @return the data */ - Object getData() { + public Object getData() { return m_data; } - - - /** - * Key. - */ - private final String m_key; - - - /** - * Semantic. - */ - private final int m_semantic; - - - /** - * Index. - */ - private final int m_index; - - - /** - * Type. - */ - private final PropertyType m_type; - - - /** - * Data. - */ - private final Object m_data; } @@ -1185,18 +1195,5 @@ public final class AiMaterial { @SuppressWarnings("unused") private void setTextureNumber(int type, int number) { m_numTextures.put(AiTextureType.fromRawValue(type), number); - } - - - /** - * List of properties. - */ - private final List m_properties = new ArrayList(); - - - /** - * Number of textures for each type. - */ - private final Map m_numTextures = - new EnumMap(AiTextureType.class); + } } diff --git a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiMesh.java b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiMesh.java index b6a478d18c..3f4a29760a 100644 --- a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiMesh.java +++ b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiMesh.java @@ -153,6 +153,89 @@ public final class AiMesh { private final int SIZEOF_V3D = Jassimp.NATIVE_AIVEKTOR3D_SIZE; + /** + * The primitive types used by this mesh. + */ + private final Set m_primitiveTypes = + EnumSet.noneOf(AiPrimitiveType.class); + + + /** + * Number of vertices in this mesh. + */ + private int m_numVertices = 0; + + + /** + * Number of faces in this mesh. + */ + private int m_numFaces = 0; + + /** + * Material used by this mesh. + */ + private int m_materialIndex = -1; + + /** + * The name of the mesh. + */ + private String m_name = ""; + + /** + * Buffer for vertex position data. + */ + private ByteBuffer m_vertices = null; + + /** + * Buffer for faces/ indices. + */ + private ByteBuffer m_faces = null; + + + /** + * Index structure for m_faces.

    + * + * Only used by meshes that are not pure triangular + */ + private ByteBuffer m_faceOffsets = null; + + /** + * Buffer for normals. + */ + private ByteBuffer m_normals = null; + + /** + * Buffer for tangents. + */ + private ByteBuffer m_tangents = null; + + /** + * Buffer for bitangents. + */ + private ByteBuffer m_bitangents = null; + + /** + * Vertex colors. + */ + private ByteBuffer[] m_colorsets = + new ByteBuffer[JassimpConfig.MAX_NUMBER_COLORSETS]; + + /** + * Number of UV components for each texture coordinate set. + */ + private int[] m_numUVComponents = new int[JassimpConfig.MAX_NUMBER_TEXCOORDS]; + + /** + * Texture coordinates. + */ + private ByteBuffer[] m_texcoords = + new ByteBuffer[JassimpConfig.MAX_NUMBER_TEXCOORDS]; + + /** + * Bones. + */ + private final List m_bones = new ArrayList(); + /** * This class is instantiated via JNI, no accessible constructor. */ @@ -1335,99 +1418,4 @@ public final class AiMesh { } } // }} - - - /** - * The primitive types used by this mesh. - */ - private final Set m_primitiveTypes = - EnumSet.noneOf(AiPrimitiveType.class); - - - /** - * Number of vertices in this mesh. - */ - private int m_numVertices = 0; - - - /** - * Number of faces in this mesh. - */ - private int m_numFaces = 0; - - - /** - * Material used by this mesh. - */ - private int m_materialIndex = -1; - - - /** - * The name of the mesh. - */ - private String m_name = ""; - - - /** - * Buffer for vertex position data. - */ - private ByteBuffer m_vertices = null; - - - /** - * Buffer for faces/ indices. - */ - private ByteBuffer m_faces = null; - - - /** - * Index structure for m_faces.

    - * - * Only used by meshes that are not pure triangular - */ - private ByteBuffer m_faceOffsets = null; - - - /** - * Buffer for normals. - */ - private ByteBuffer m_normals = null; - - - /** - * Buffer for tangents. - */ - private ByteBuffer m_tangents = null; - - - /** - * Buffer for bitangents. - */ - private ByteBuffer m_bitangents = null; - - - /** - * Vertex colors. - */ - private ByteBuffer[] m_colorsets = - new ByteBuffer[JassimpConfig.MAX_NUMBER_COLORSETS]; - - - /** - * Number of UV components for each texture coordinate set. - */ - private int[] m_numUVComponents = new int[JassimpConfig.MAX_NUMBER_TEXCOORDS]; - - - /** - * Texture coordinates. - */ - private ByteBuffer[] m_texcoords = - new ByteBuffer[JassimpConfig.MAX_NUMBER_TEXCOORDS]; - - - /** - * Bones. - */ - private final List m_bones = new ArrayList(); } diff --git a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiNode.java b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiNode.java index 9345b7af45..e585e0449b 100644 --- a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiNode.java +++ b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiNode.java @@ -55,6 +55,34 @@ import java.util.Map; * the imported scene consists of only a single root node without children. */ public final class AiNode { + /** + * Parent node. + */ + private final AiNode m_parent; + + + /** + * Mesh references. + */ + private final int[] m_meshReferences; + + + /** + * List of children. + */ + private final List m_children = new ArrayList(); + + /** + * List of metadata entries. + */ + private final Map m_metaData = new HashMap(); + + + /** + * Buffer for transformation matrix. + */ + private final Object m_transformationMatrix; + /** * Constructor. * @@ -214,34 +242,5 @@ public final class AiNode { /** * Name. */ - private final String m_name; - - - /** - * Parent node. - */ - private final AiNode m_parent; - - - /** - * Mesh references. - */ - private final int[] m_meshReferences; - - - /** - * List of children. - */ - private final List m_children = new ArrayList(); - - /** - * List of metadata entries. - */ - private final Map m_metaData = new HashMap(); - - - /** - * Buffer for transformation matrix. - */ - private final Object m_transformationMatrix; + private final String m_name; } diff --git a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiProgressHandler.java b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiProgressHandler.java new file mode 100644 index 0000000000..5512942d9a --- /dev/null +++ b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiProgressHandler.java @@ -0,0 +1,46 @@ +/* +--------------------------------------------------------------------------- +Open Asset Import Library - Java Binding (jassimp) +--------------------------------------------------------------------------- + +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. +--------------------------------------------------------------------------- +*/ +package jassimp; + +public interface AiProgressHandler +{ + boolean update(float percentage); +} \ No newline at end of file diff --git a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiQuaternion.java b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiQuaternion.java index de162631b1..00630e6447 100644 --- a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiQuaternion.java +++ b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiQuaternion.java @@ -50,6 +50,17 @@ import java.nio.ByteBuffer; * modify the underlying mesh/animation. */ public final class AiQuaternion { + /** + * Wrapped buffer. + */ + private final ByteBuffer m_buffer; + + + /** + * Offset into m_buffer. + */ + private final int m_offset; + /** * Constructor. * @@ -150,17 +161,5 @@ public final class AiQuaternion { public String toString() { return "[" + getX() + ", " + getY() + ", " + getZ() + ", " + getW() + "]"; - } - - - /** - * Wrapped buffer. - */ - private final ByteBuffer m_buffer; - - - /** - * Offset into m_buffer. - */ - private final int m_offset; + } } \ No newline at end of file diff --git a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiSceneFlag.java b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiSceneFlag.java index 7f7e01ea99..af3ee5d5f4 100644 --- a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiSceneFlag.java +++ b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/AiSceneFlag.java @@ -114,8 +114,12 @@ public enum AiSceneFlag { * you actually need to render it). */ TERRAIN(0x10); - - + + /** + * The mapped c/c++ integer enum value. + */ + private final int m_rawValue; + /** * Utility method for converting from c/c++ based integer enums to java * enums.

    @@ -143,11 +147,5 @@ public enum AiSceneFlag { */ private AiSceneFlag(int rawValue) { m_rawValue = rawValue; - } - - - /** - * The mapped c/c++ integer enum value. - */ - private final int m_rawValue; + } } diff --git a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/Jassimp.java b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/Jassimp.java index d1b4aae4e2..c33f95c0a4 100644 --- a/third_party/libassimp/port/jassimp/jassimp/src/jassimp/Jassimp.java +++ b/third_party/libassimp/port/jassimp/jassimp/src/jassimp/Jassimp.java @@ -60,6 +60,45 @@ import java.util.Set; */ public final class Jassimp { + /** + * The native interface. + * + * @param filename the file to load + * @param postProcessing post processing flags + * @return the loaded scene, or null if an error occurred + * @throws IOException if an error occurs + */ + private static native AiScene aiImportFile(String filename, + long postProcessing, AiIOSystem ioSystem, + AiProgressHandler progressHandler) throws IOException; + + + /** + * The active wrapper provider. + */ + private static AiWrapperProvider s_wrapperProvider = + new AiBuiltInWrapperProvider(); + + + /** + * The library loader to load the native library. + */ + private static JassimpLibraryLoader s_libraryLoader = + new JassimpLibraryLoader(); + + /** + * Status flag if the library is loaded. + * + * Volatile to avoid problems with double checked locking. + * + */ + private static volatile boolean s_libraryLoaded = false; + + /** + * Lock for library loading. + */ + private static final Object s_libraryLoadingLock = new Object(); + /** * The default wrapper provider using built in types. */ @@ -120,11 +159,26 @@ public final class Jassimp { public static AiScene importFile(String filename, Set postProcessing, AiIOSystem ioSystem) throws IOException { - - loadLibrary(); - + return importFile(filename, postProcessing, ioSystem, null); + } + + /** + * Imports a file via assimp. + * + * @param filename the file to import + * @param postProcessing post processing flags + * @param ioSystem ioSystem to load files, or null for default + * @return the loaded scene, or null if an error occurred + * @throws IOException if an error occurs + */ + public static AiScene importFile(String filename, + Set postProcessing, AiIOSystem ioSystem, + AiProgressHandler progressHandler) throws IOException { + + loadLibrary(); + return aiImportFile(filename, AiPostProcessSteps.toRawValue( - postProcessing), ioSystem); + postProcessing), ioSystem, progressHandler); } @@ -327,48 +381,9 @@ public final class Jassimp { s_libraryLoaded = true; } } - } } - - /** - * The native interface. - * - * @param filename the file to load - * @param postProcessing post processing flags - * @return the loaded scene, or null if an error occurred - * @throws IOException if an error occurs - */ - private static native AiScene aiImportFile(String filename, - long postProcessing, AiIOSystem ioSystem) throws IOException; - - - /** - * The active wrapper provider. - */ - private static AiWrapperProvider s_wrapperProvider = - new AiBuiltInWrapperProvider(); - - - /** - * The library loader to load the native library. - */ - private static JassimpLibraryLoader s_libraryLoader = - new JassimpLibraryLoader(); - - /** - * Status flag if the library is loaded. - * - * Volatile to avoid problems with double checked locking. - * - */ - private static volatile boolean s_libraryLoaded = false; - - /** - * Lock for library loading. - */ - private static final Object s_libraryLoadingLock = new Object(); - + /** * Pure static class, no accessible constructor. */ @@ -384,5 +399,4 @@ public final class Jassimp { public static int NATIVE_UINT_SIZE; public static int NATIVE_DOUBLE_SIZE; public static int NATIVE_LONG_SIZE; - } diff --git a/third_party/libassimp/revision.h b/third_party/libassimp/revision.h index 4ee64a2fbf..a66fe773a6 100644 --- a/third_party/libassimp/revision.h +++ b/third_party/libassimp/revision.h @@ -1,7 +1,28 @@ #ifndef ASSIMP_REVISION_H_INC #define ASSIMP_REVISION_H_INC -#define GitVersion 0xd7eae5bb +#define GitVersion 0x4673545f #define GitBranch "master" +#define VER_MAJOR 5 +#define VER_MINOR 0 +#define VER_PATCH 0 +#define VER_BUILD 0 + +#define STR_HELP(x) #x +#define STR(x) STR_HELP(x) + +#define VER_FILEVERSION VER_MAJOR,VER_MINOR,VER_PATCH,VER_BUILD +#if (GitVersion == 0) +#define VER_FILEVERSION_STR STR(VER_MAJOR) "." STR(VER_MINOR) "." STR(VER_PATCH) "." STR(VER_BUILD) +#else +#define VER_FILEVERSION_STR STR(VER_MAJOR) "." STR(VER_MINOR) "." STR(VER_PATCH) "." STR(VER_BUILD) " (Commit 4673545f)" +#endif + +#ifdef NDEBUG +#define VER_ORIGINAL_FILENAME_STR "assimp.dll" +#else +#define VER_ORIGINAL_FILENAME_STR "assimp.dll" +#endif // NDEBUG + #endif // ASSIMP_REVISION_H_INC diff --git a/third_party/libassimp/revision.h.in b/third_party/libassimp/revision.h.in index 87c41fa89b..6d09afbc63 100644 --- a/third_party/libassimp/revision.h.in +++ b/third_party/libassimp/revision.h.in @@ -4,4 +4,25 @@ #define GitVersion 0x@GIT_COMMIT_HASH@ #define GitBranch "@GIT_BRANCH@" +#define VER_MAJOR @ASSIMP_VERSION_MAJOR@ +#define VER_MINOR @ASSIMP_VERSION_MINOR@ +#define VER_PATCH @ASSIMP_VERSION_PATCH@ +#define VER_BUILD @ASSIMP_PACKAGE_VERSION@ + +#define STR_HELP(x) #x +#define STR(x) STR_HELP(x) + +#define VER_FILEVERSION VER_MAJOR,VER_MINOR,VER_PATCH,VER_BUILD +#if (GitVersion == 0) +#define VER_FILEVERSION_STR STR(VER_MAJOR) "." STR(VER_MINOR) "." STR(VER_PATCH) "." STR(VER_BUILD) +#else +#define VER_FILEVERSION_STR STR(VER_MAJOR) "." STR(VER_MINOR) "." STR(VER_PATCH) "." STR(VER_BUILD) " (Commit @GIT_COMMIT_HASH@)" +#endif + +#ifdef NDEBUG +#define VER_ORIGINAL_FILENAME_STR "assimp@LIBRARY_SUFFIX@.dll" +#else +#define VER_ORIGINAL_FILENAME_STR "assimp@LIBRARY_SUFFIX@@CMAKE_DEBUG_POSTFIX@.dll" +#endif // NDEBUG + #endif // ASSIMP_REVISION_H_INC diff --git a/third_party/libassimp/scripts/BlenderImporter/genblenddna.py b/third_party/libassimp/scripts/BlenderImporter/genblenddna.py index caa58ded7d..cca595eca7 100644 --- a/third_party/libassimp/scripts/BlenderImporter/genblenddna.py +++ b/third_party/libassimp/scripts/BlenderImporter/genblenddna.py @@ -291,7 +291,9 @@ def main(): #s += "#endif\n" output.write(templt.replace("",s)) - + + # we got here, so no error + return 0 if __name__ == "__main__": sys.exit(main()) diff --git a/third_party/libassimp/scripts/StepImporter/CppGenerator.py b/third_party/libassimp/scripts/StepImporter/CppGenerator.py index 156f195235..b9dba99028 100644 --- a/third_party/libassimp/scripts/StepImporter/CppGenerator.py +++ b/third_party/libassimp/scripts/StepImporter/CppGenerator.py @@ -52,8 +52,8 @@ use_ifc_template = False input_step_template_h = 'StepReaderGen.h.template' input_step_template_cpp = 'StepReaderGen.cpp.template' -input_ifc_template_h = 'IFCReaderGen.h.template' -input_ifc_template_cpp = 'IFCReaderGen.cpp.template' +input_ifc_template_h = 'IFCReaderGen.h.template' +input_ifc_template_cpp = 'IFCReaderGen.cpp.template' cpp_keywords = "class" @@ -87,7 +87,7 @@ template_type = r""" template_stub_decl = '\tDECL_CONV_STUB({type});\n' template_schema = '\t\tSchemaEntry("{normalized_name}",&STEP::ObjectHelper<{type},{argcnt}>::Construct )\n' -template_schema_type = '\t\tSchemaEntry("{normalized_name}",NULL )\n' +template_schema_type = '\t\tSchemaEntry("{normalized_name}",nullptr )\n' template_converter = r""" // ----------------------------------------------------------------------------------------------------------- template <> size_t GenericFill<{type}>(const DB& db, const LIST& params, {type}* in) @@ -99,7 +99,7 @@ template_converter_prologue_a = '\tsize_t base = GenericFill(db,params,static_ca template_converter_prologue_b = '\tsize_t base = 0;\n' template_converter_check_argcnt = '\tif (params.GetSize() < {max_arg}) {{ throw STEP::TypeError("expected {max_arg} arguments to {name}"); }}' template_converter_code_per_field = r""" do {{ // convert the '{fieldname}' argument - boost::shared_ptr arg = params[base++];{handle_unset}{convert} + std::shared_ptr arg = params[base++];{handle_unset}{convert} }} while(0); """ template_allow_optional = r""" @@ -151,11 +151,8 @@ def handle_unset_args(field,entity,schema,argnum): return n+template_allow_optional.format() def get_single_conversion(field,schema,argnum=0,classname='?'): - typen = field.type name = field.name - if field.collection: - typen = 'LIST' - return template_convert_single.format(type=typen,name=name,argnum=argnum,classname=classname,full_type=field.fullspec) + return template_convert_single.format(name=name,argnum=argnum,classname=classname,full_type=field.fullspec) def count_args_up(entity,schema): return len(entity.members) + (count_args_up(schema.entities[entity.parent],schema) if entity.parent else 0) @@ -218,7 +215,7 @@ def get_derived(e,schema): return res def get_hierarchy(e,schema): - return get_derived(e.schema)+[e.name]+get_base_classes(e,schema) + return get_derived(e, schema)+[e.name]+get_base_classes(e,schema) def sort_entity_list(schema): deps = [] @@ -300,5 +297,8 @@ def work(filename): with open(output_file_cpp,'wt') as outp: outp.write(inp.read().replace('{schema-static-table}',schema_table).replace('{converter-impl}',converters)) + # Finished without error, so return 0 + return 0 + if __name__ == "__main__": sys.exit(work(sys.argv[1] if len(sys.argv)>1 else 'schema.exp')) diff --git a/third_party/libassimp/scripts/StepImporter/ExpressReader.py b/third_party/libassimp/scripts/StepImporter/ExpressReader.py index 84aaadbdc6..c2a39e70b8 100644 --- a/third_party/libassimp/scripts/StepImporter/ExpressReader.py +++ b/third_party/libassimp/scripts/StepImporter/ExpressReader.py @@ -43,7 +43,8 @@ """Parse an EXPRESS file and extract basic information on all entities and data types contained""" -import sys, os, re +import sys +import re from collections import OrderedDict re_match_entity = re.compile(r""" diff --git a/third_party/libassimp/scripts/StepImporter/StepReaderGen.cpp.template b/third_party/libassimp/scripts/StepImporter/StepReaderGen.cpp.template index 343c43019b..f3240c099b 100644 --- a/third_party/libassimp/scripts/StepImporter/StepReaderGen.cpp.template +++ b/third_party/libassimp/scripts/StepImporter/StepReaderGen.cpp.template @@ -2,7 +2,7 @@ Open Asset Import Library (ASSIMP) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, ASSIMP Development Team +Copyright (c) 2006-2019, ASSIMP Development Team All rights reserved. Redistribution and use of this software in source and binary forms, @@ -40,7 +40,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** MACHINE-GENERATED by scripts/ICFImporter/CppGenerator.py */ -#ifndef ASSIMP_BUILD_NO_STEPFILE_IMPORTER +#ifndef ASSIMP_BUILD_NO_STEP_IMPORTER #include "code/Importer/StepFile/StepReaderGen.h" @@ -66,7 +66,7 @@ namespace STEP { // ----------------------------------------------------------------------------------------------------------- template <> size_t GenericFill(const STEP::DB& db, const LIST& params, NotImplemented* in) { - return 0; + return 0u; } diff --git a/third_party/libassimp/scripts/StepImporter/StepReaderGen.h.template b/third_party/libassimp/scripts/StepImporter/StepReaderGen.h.template index 5f9a2fd5d9..7d4d77ef40 100644 --- a/third_party/libassimp/scripts/StepImporter/StepReaderGen.h.template +++ b/third_party/libassimp/scripts/StepImporter/StepReaderGen.h.template @@ -2,7 +2,7 @@ Open Asset Import Library (ASSIMP) ---------------------------------------------------------------------- -Copyright (c) 2006-2018, ASSIMP Development Team +Copyright (c) 2006-2019, ASSIMP Development Team All rights reserved. Redistribution and use of this software in source and binary forms, @@ -47,25 +47,23 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. namespace Assimp { namespace StepFile { - using namespace STEP; - using namespace STEP::EXPRESS; - - - struct NotImplemented : public ObjectHelper { - - }; - - // ****************************************************************************** - // StepFile Custom data types - // ****************************************************************************** +using namespace STEP; +using namespace STEP::EXPRESS; + +struct NotImplemented : public ObjectHelper { + +}; + +// ****************************************************************************** +// StepFile Custom data types +// ****************************************************************************** {types} - - // ****************************************************************************** - // StepFile Entities - // ****************************************************************************** +// ****************************************************************************** +// StepFile Entities +// ****************************************************************************** {predefs} {entities} @@ -73,11 +71,12 @@ namespace StepFile { void GetSchema(EXPRESS::ConversionSchema& out); } //! StepFile + namespace STEP { - // ****************************************************************************** - // Converter stubs - // ****************************************************************************** +// ****************************************************************************** +// Converter stubs +// ****************************************************************************** #define DECL_CONV_STUB(type) template <> size_t GenericFill(const STEP::DB& db, const EXPRESS::LIST& params, IFC::type* in) diff --git a/third_party/libassimp/tnt/CMakeLists.txt b/third_party/libassimp/tnt/CMakeLists.txt index c37c05b316..8ed3d48f40 100644 --- a/third_party/libassimp/tnt/CMakeLists.txt +++ b/third_party/libassimp/tnt/CMakeLists.txt @@ -42,146 +42,147 @@ set(PUBLIC_HDRS # private headers dependencies set(PRIVATE_HDRS - ${PRIVATE_HDR_DIR}/BaseProcess.h - ${PRIVATE_HDR_DIR}/CInterfaceIOWrapper.h - ${PRIVATE_HDR_DIR}/CalcTangentsProcess.h - ${PRIVATE_HDR_DIR}/ComputeUVMappingProcess.h - ${PRIVATE_HDR_DIR}/ConvertToLHProcess.h - ${PRIVATE_HDR_DIR}/DeboneProcess.h - ${PRIVATE_HDR_DIR}/DefaultProgressHandler.h - ${PRIVATE_HDR_DIR}/DropFaceNormalsProcess.h - ${PRIVATE_HDR_DIR}/EmbedTexturesProcess.h - ${PRIVATE_HDR_DIR}/FBXCommon.h - ${PRIVATE_HDR_DIR}/FBXCompileConfig.h - ${PRIVATE_HDR_DIR}/FBXConverter.h - ${PRIVATE_HDR_DIR}/FBXDocument.h - ${PRIVATE_HDR_DIR}/FBXDocumentUtil.h - ${PRIVATE_HDR_DIR}/FBXImportSettings.h - ${PRIVATE_HDR_DIR}/FBXImporter.h - ${PRIVATE_HDR_DIR}/FBXMeshGeometry.h - ${PRIVATE_HDR_DIR}/FBXParser.h - ${PRIVATE_HDR_DIR}/FBXProperties.h - ${PRIVATE_HDR_DIR}/FBXTokenizer.h - ${PRIVATE_HDR_DIR}/FBXUtil.h - ${PRIVATE_HDR_DIR}/FileLogStream.h - ${PRIVATE_HDR_DIR}/FileSystemFilter.h - ${PRIVATE_HDR_DIR}/FindDegenerates.h - ${PRIVATE_HDR_DIR}/FindInstancesProcess.h - ${PRIVATE_HDR_DIR}/FindInvalidDataProcess.h - ${PRIVATE_HDR_DIR}/FixNormalsStep.h - ${PRIVATE_HDR_DIR}/GenFaceNormalsProcess.h - ${PRIVATE_HDR_DIR}/GenVertexNormalsProcess.h - ${PRIVATE_HDR_DIR}/IFF.h - ${PRIVATE_HDR_DIR}/Importer.h - ${PRIVATE_HDR_DIR}/ImproveCacheLocality.h - ${PRIVATE_HDR_DIR}/JoinVerticesProcess.h - ${PRIVATE_HDR_DIR}/LimitBoneWeightsProcess.h - ${PRIVATE_HDR_DIR}/MakeVerboseFormat.h - ${PRIVATE_HDR_DIR}/MaterialSystem.h - ${PRIVATE_HDR_DIR}/ObjFileData.h - ${PRIVATE_HDR_DIR}/ObjFileImporter.h - ${PRIVATE_HDR_DIR}/ObjFileMtlImporter.h - ${PRIVATE_HDR_DIR}/ObjFileParser.h - ${PRIVATE_HDR_DIR}/ObjTools.h - ${PRIVATE_HDR_DIR}/OptimizeGraph.h - ${PRIVATE_HDR_DIR}/OptimizeMeshes.h - ${PRIVATE_HDR_DIR}/PolyTools.h - ${PRIVATE_HDR_DIR}/PretransformVertices.h - ${PRIVATE_HDR_DIR}/ProcessHelper.h - ${PRIVATE_HDR_DIR}/RemoveRedundantMaterials.h - ${PRIVATE_HDR_DIR}/RemoveVCProcess.h - ${PRIVATE_HDR_DIR}/ScaleProcess.h - ${PRIVATE_HDR_DIR}/ScenePreprocessor.h - ${PRIVATE_HDR_DIR}/ScenePrivate.h - ${PRIVATE_HDR_DIR}/SortByPTypeProcess.h - ${PRIVATE_HDR_DIR}/SplitByBoneCountProcess.h - ${PRIVATE_HDR_DIR}/SplitLargeMeshes.h - ${PRIVATE_HDR_DIR}/StdOStreamLogStream.h - ${PRIVATE_HDR_DIR}/TargetAnimation.h - ${PRIVATE_HDR_DIR}/TextureTransform.h - ${PRIVATE_HDR_DIR}/TriangulateProcess.h - ${PRIVATE_HDR_DIR}/ValidateDataStructure.h - ${PRIVATE_HDR_DIR}/VertexTriangleAdjacency.h - ${PRIVATE_HDR_DIR}/Win32DebugLogStream.h - ${PRIVATE_HDR_DIR}/assbin_chunks.h + ${PRIVATE_HDR_DIR}/Common/BaseProcess.h + ${PRIVATE_HDR_DIR}/CApi/CInterfaceIOWrapper.h + ${PRIVATE_HDR_DIR}/PostProcessing/CalcTangentsProcess.h + ${PRIVATE_HDR_DIR}/PostProcessing/ComputeUVMappingProcess.h + ${PRIVATE_HDR_DIR}/PostProcessing/ConvertToLHProcess.h + ${PRIVATE_HDR_DIR}/PostProcessing/DeboneProcess.h + ${PRIVATE_HDR_DIR}/Common/DefaultProgressHandler.h + ${PRIVATE_HDR_DIR}/PostProcessing/DropFaceNormalsProcess.h + ${PRIVATE_HDR_DIR}/PostProcessing/EmbedTexturesProcess.h + ${PRIVATE_HDR_DIR}/FBX/FBXCommon.h + ${PRIVATE_HDR_DIR}/FBX/FBXCompileConfig.h + ${PRIVATE_HDR_DIR}/FBX/FBXConverter.h + ${PRIVATE_HDR_DIR}/FBX/FBXDocument.h + ${PRIVATE_HDR_DIR}/FBX/FBXDocumentUtil.h + ${PRIVATE_HDR_DIR}/FBX/FBXImportSettings.h + ${PRIVATE_HDR_DIR}/FBX/FBXImporter.h + ${PRIVATE_HDR_DIR}/FBX/FBXMeshGeometry.h + ${PRIVATE_HDR_DIR}/FBX/FBXParser.h + ${PRIVATE_HDR_DIR}/FBX/FBXProperties.h + ${PRIVATE_HDR_DIR}/FBX/FBXTokenizer.h + ${PRIVATE_HDR_DIR}/FBX/FBXUtil.h + ${PRIVATE_HDR_DIR}/Common/FileLogStream.h + ${PRIVATE_HDR_DIR}/Common/FileSystemFilter.h + ${PRIVATE_HDR_DIR}/PostProcessing/FindDegenerates.h + ${PRIVATE_HDR_DIR}/PostProcessing/FindInstancesProcess.h + ${PRIVATE_HDR_DIR}/PostProcessing/FindInvalidDataProcess.h + ${PRIVATE_HDR_DIR}/PostProcessing/FixNormalsStep.h + ${PRIVATE_HDR_DIR}/PostProcessing/GenFaceNormalsProcess.h + ${PRIVATE_HDR_DIR}/PostProcessing/GenVertexNormalsProcess.h + ${PRIVATE_HDR_DIR}/Common/IFF.h + ${PRIVATE_HDR_DIR}/Common/Importer.h + ${PRIVATE_HDR_DIR}/PostProcessing/ImproveCacheLocality.h + ${PRIVATE_HDR_DIR}/PostProcessing/JoinVerticesProcess.h + ${PRIVATE_HDR_DIR}/PostProcessing/LimitBoneWeightsProcess.h + ${PRIVATE_HDR_DIR}/PostProcessing/MakeVerboseFormat.h + ${PRIVATE_HDR_DIR}/Material/MaterialSystem.h + ${PRIVATE_HDR_DIR}/Obj/ObjFileData.h + ${PRIVATE_HDR_DIR}/Obj/ObjFileImporter.h + ${PRIVATE_HDR_DIR}/Obj/ObjFileMtlImporter.h + ${PRIVATE_HDR_DIR}/Obj/ObjFileParser.h + ${PRIVATE_HDR_DIR}/Obj/ObjTools.h + ${PRIVATE_HDR_DIR}/PostProcessing/OptimizeGraph.h + ${PRIVATE_HDR_DIR}/PostProcessing/OptimizeMeshes.h + ${PRIVATE_HDR_DIR}/Common/PolyTools.h + ${PRIVATE_HDR_DIR}/PostProcessing/PretransformVertices.h + ${PRIVATE_HDR_DIR}/PostProcessing/ProcessHelper.h + ${PRIVATE_HDR_DIR}/PostProcessing/RemoveRedundantMaterials.h + ${PRIVATE_HDR_DIR}/PostProcessing/RemoveVCProcess.h + ${PRIVATE_HDR_DIR}/PostProcessing/ScaleProcess.h + ${PRIVATE_HDR_DIR}/Common/ScenePreprocessor.h + ${PRIVATE_HDR_DIR}/Common/ScenePrivate.h + ${PRIVATE_HDR_DIR}/PostProcessing/SortByPTypeProcess.h + ${PRIVATE_HDR_DIR}/Common/SplitByBoneCountProcess.h + ${PRIVATE_HDR_DIR}/PostProcessing/SplitLargeMeshes.h + ${PRIVATE_HDR_DIR}/Common/StdOStreamLogStream.h + ${PRIVATE_HDR_DIR}/Common/TargetAnimation.h + ${PRIVATE_HDR_DIR}/PostProcessing/TextureTransform.h + ${PRIVATE_HDR_DIR}/PostProcessing/TriangulateProcess.h + ${PRIVATE_HDR_DIR}/PostProcessing/ValidateDataStructure.h + ${PRIVATE_HDR_DIR}/Common/VertexTriangleAdjacency.h + ${PRIVATE_HDR_DIR}/Common/Win32DebugLogStream.h + ${PRIVATE_HDR_DIR}/Common/assbin_chunks.h ) # sources dependencies set(SRCS - ${SRC_DIR}/code/Assimp.cpp - ${SRC_DIR}/code/BaseImporter.cpp - ${SRC_DIR}/code/BaseProcess.cpp - ${SRC_DIR}/code/Bitmap.cpp - ${SRC_DIR}/code/CInterfaceIOWrapper.cpp - ${SRC_DIR}/code/CalcTangentsProcess.cpp - ${SRC_DIR}/code/ComputeUVMappingProcess.cpp - ${SRC_DIR}/code/ConvertToLHProcess.cpp - ${SRC_DIR}/code/CreateAnimMesh.cpp - ${SRC_DIR}/code/DeboneProcess.cpp - ${SRC_DIR}/code/DefaultIOStream.cpp - ${SRC_DIR}/code/DefaultIOSystem.cpp - ${SRC_DIR}/code/DefaultLogger.cpp - ${SRC_DIR}/code/DropFaceNormalsProcess.cpp - ${SRC_DIR}/code/EmbedTexturesProcess.cpp - ${SRC_DIR}/code/Exporter.cpp - ${SRC_DIR}/code/FBXAnimation.cpp - ${SRC_DIR}/code/FBXBinaryTokenizer.cpp - ${SRC_DIR}/code/FBXConverter.cpp - ${SRC_DIR}/code/FBXDeformer.cpp - ${SRC_DIR}/code/FBXDocument.cpp - ${SRC_DIR}/code/FBXDocumentUtil.cpp - ${SRC_DIR}/code/FBXImporter.cpp - ${SRC_DIR}/code/FBXMaterial.cpp - ${SRC_DIR}/code/FBXMeshGeometry.cpp - ${SRC_DIR}/code/FBXModel.cpp - ${SRC_DIR}/code/FBXNodeAttribute.cpp - ${SRC_DIR}/code/FBXParser.cpp - ${SRC_DIR}/code/FBXProperties.cpp - ${SRC_DIR}/code/FBXTokenizer.cpp - ${SRC_DIR}/code/FBXUtil.cpp - ${SRC_DIR}/code/FIReader.cpp - ${SRC_DIR}/code/FindDegenerates.cpp - ${SRC_DIR}/code/FindInstancesProcess.cpp - ${SRC_DIR}/code/FindInvalidDataProcess.cpp - ${SRC_DIR}/code/FixNormalsStep.cpp - ${SRC_DIR}/code/GenFaceNormalsProcess.cpp - ${SRC_DIR}/code/GenVertexNormalsProcess.cpp - ${SRC_DIR}/code/Importer.cpp - ${SRC_DIR}/code/ImporterRegistry.cpp - ${SRC_DIR}/code/ImproveCacheLocality.cpp - ${SRC_DIR}/code/JoinVerticesProcess.cpp - ${SRC_DIR}/code/LimitBoneWeightsProcess.cpp - ${SRC_DIR}/code/MakeVerboseFormat.cpp - ${SRC_DIR}/code/MaterialSystem.cpp - ${SRC_DIR}/code/ObjFileImporter.cpp - ${SRC_DIR}/code/ObjFileMtlImporter.cpp - ${SRC_DIR}/code/ObjFileParser.cpp - ${SRC_DIR}/code/OptimizeGraph.cpp - ${SRC_DIR}/code/OptimizeMeshes.cpp - ${SRC_DIR}/code/PostStepRegistry.cpp - ${SRC_DIR}/code/PretransformVertices.cpp - ${SRC_DIR}/code/ProcessHelper.cpp - ${SRC_DIR}/code/RemoveComments.cpp - ${SRC_DIR}/code/RemoveRedundantMaterials.cpp - ${SRC_DIR}/code/RemoveVCProcess.cpp - ${SRC_DIR}/code/SGSpatialSort.cpp - ${SRC_DIR}/code/ScaleProcess.cpp - ${SRC_DIR}/code/SceneCombiner.cpp - ${SRC_DIR}/code/ScenePreprocessor.cpp - ${SRC_DIR}/code/SkeletonMeshBuilder.cpp - ${SRC_DIR}/code/SortByPTypeProcess.cpp - ${SRC_DIR}/code/SpatialSort.cpp - ${SRC_DIR}/code/SplitByBoneCountProcess.cpp - ${SRC_DIR}/code/SplitLargeMeshes.cpp - ${SRC_DIR}/code/StandardShapes.cpp - ${SRC_DIR}/code/Subdivision.cpp - ${SRC_DIR}/code/TargetAnimation.cpp - ${SRC_DIR}/code/TextureTransform.cpp - ${SRC_DIR}/code/TriangulateProcess.cpp - ${SRC_DIR}/code/ValidateDataStructure.cpp - ${SRC_DIR}/code/Version.cpp - ${SRC_DIR}/code/VertexTriangleAdjacency.cpp - ${SRC_DIR}/code/scene.cpp + ${SRC_DIR}/code/Common/Assimp.cpp + ${SRC_DIR}/code/Common/BaseImporter.cpp + ${SRC_DIR}/code/Common/BaseProcess.cpp + ${SRC_DIR}/code/Common/Bitmap.cpp + ${SRC_DIR}/code/CApi/CInterfaceIOWrapper.cpp + ${SRC_DIR}/code/PostProcessing/CalcTangentsProcess.cpp + ${SRC_DIR}/code/PostProcessing/ComputeUVMappingProcess.cpp + ${SRC_DIR}/code/PostProcessing/ConvertToLHProcess.cpp + ${SRC_DIR}/code/Common/CreateAnimMesh.cpp + ${SRC_DIR}/code/PostProcessing/DeboneProcess.cpp + ${SRC_DIR}/code/Common/DefaultIOStream.cpp + ${SRC_DIR}/code/Common/DefaultIOSystem.cpp + ${SRC_DIR}/code/Common/DefaultLogger.cpp + ${SRC_DIR}/code/PostProcessing/DropFaceNormalsProcess.cpp + ${SRC_DIR}/code/PostProcessing/EmbedTexturesProcess.cpp + ${SRC_DIR}/code/Common/Exporter.cpp + ${SRC_DIR}/code/FBX/FBXAnimation.cpp + ${SRC_DIR}/code/FBX/FBXBinaryTokenizer.cpp + ${SRC_DIR}/code/FBX/FBXConverter.cpp + ${SRC_DIR}/code/FBX/FBXDeformer.cpp + ${SRC_DIR}/code/FBX/FBXDocument.cpp + ${SRC_DIR}/code/FBX/FBXDocumentUtil.cpp + ${SRC_DIR}/code/FBX/FBXImporter.cpp + ${SRC_DIR}/code/FBX/FBXMaterial.cpp + ${SRC_DIR}/code/FBX/FBXMeshGeometry.cpp + ${SRC_DIR}/code/FBX/FBXModel.cpp + ${SRC_DIR}/code/FBX/FBXNodeAttribute.cpp + ${SRC_DIR}/code/FBX/FBXParser.cpp + ${SRC_DIR}/code/FBX/FBXProperties.cpp + ${SRC_DIR}/code/FBX/FBXTokenizer.cpp + ${SRC_DIR}/code/FBX/FBXUtil.cpp + ${SRC_DIR}/code/X3D/FIReader.cpp + ${SRC_DIR}/code/PostProcessing/FindDegenerates.cpp + ${SRC_DIR}/code/PostProcessing/FindInstancesProcess.cpp + ${SRC_DIR}/code/PostProcessing/FindInvalidDataProcess.cpp + ${SRC_DIR}/code/PostProcessing/FixNormalsStep.cpp + ${SRC_DIR}/code/PostProcessing/GenFaceNormalsProcess.cpp + ${SRC_DIR}/code/PostProcessing/GenBoundingBoxesProcess.cpp + ${SRC_DIR}/code/PostProcessing/GenVertexNormalsProcess.cpp + ${SRC_DIR}/code/Common/Importer.cpp + ${SRC_DIR}/code/Common/ImporterRegistry.cpp + ${SRC_DIR}/code/PostProcessing/ImproveCacheLocality.cpp + ${SRC_DIR}/code/PostProcessing/JoinVerticesProcess.cpp + ${SRC_DIR}/code/PostProcessing/LimitBoneWeightsProcess.cpp + ${SRC_DIR}/code/PostProcessing/MakeVerboseFormat.cpp + ${SRC_DIR}/code/Material/MaterialSystem.cpp + ${SRC_DIR}/code/Obj/ObjFileImporter.cpp + ${SRC_DIR}/code/Obj/ObjFileMtlImporter.cpp + ${SRC_DIR}/code/Obj/ObjFileParser.cpp + ${SRC_DIR}/code/PostProcessing/OptimizeGraph.cpp + ${SRC_DIR}/code/PostProcessing/OptimizeMeshes.cpp + ${SRC_DIR}/code/Common/PostStepRegistry.cpp + ${SRC_DIR}/code/PostProcessing/PretransformVertices.cpp + ${SRC_DIR}/code/PostProcessing/ProcessHelper.cpp + ${SRC_DIR}/code/Common/RemoveComments.cpp + ${SRC_DIR}/code/PostProcessing/RemoveRedundantMaterials.cpp + ${SRC_DIR}/code/PostProcessing/RemoveVCProcess.cpp + ${SRC_DIR}/code/Common/SGSpatialSort.cpp + ${SRC_DIR}/code/PostProcessing/ScaleProcess.cpp + ${SRC_DIR}/code/Common/SceneCombiner.cpp + ${SRC_DIR}/code/Common/ScenePreprocessor.cpp + ${SRC_DIR}/code/Common/SkeletonMeshBuilder.cpp + ${SRC_DIR}/code/PostProcessing/SortByPTypeProcess.cpp + ${SRC_DIR}/code/Common/SpatialSort.cpp + ${SRC_DIR}/code/Common/SplitByBoneCountProcess.cpp + ${SRC_DIR}/code/PostProcessing/SplitLargeMeshes.cpp + ${SRC_DIR}/code/Common/StandardShapes.cpp + ${SRC_DIR}/code/Common/Subdivision.cpp + ${SRC_DIR}/code/Common/TargetAnimation.cpp + ${SRC_DIR}/code/PostProcessing/TextureTransform.cpp + ${SRC_DIR}/code/PostProcessing/TriangulateProcess.cpp + ${SRC_DIR}/code/PostProcessing/ValidateDataStructure.cpp + ${SRC_DIR}/code/Common/Version.cpp + ${SRC_DIR}/code/Common/VertexTriangleAdjacency.cpp + ${SRC_DIR}/code/Common/scene.cpp ${SRC_DIR}/contrib/clipper/clipper.cpp ${SRC_DIR}/contrib/irrXML/irrXML.cpp ${SRC_DIR}/contrib/poly2tri/poly2tri/common/shapes.cc @@ -243,6 +244,7 @@ add_definitions( -DASSIMP_BUILD_NO_XGL_IMPORTER -DASSIMP_BUILD_NO_X_IMPORTER -DASSIMP_BUILD_NO_XX_IMPORTER + -DASSIMP_BUILD_NO_STEP_IMPORTER -DASSIMP_BUILD_NO_EXPORTER ) @@ -254,7 +256,7 @@ add_definitions( include_directories(${SRC_DIR}/contrib/irrXML) include_directories(${SRC_DIR}/contrib/rapidjson/include) include_directories(${SRC_DIR}) -include_directories(${SRC_DIR}/code/BoostWorkaround) +include_directories(${PRIVATE_HDR_DIR}) # we're building a library add_library(${TARGET} STATIC ${PRIVATE_HDRS} ${PUBLIC_HDRS} ${SRCS}) diff --git a/third_party/libassimp/tnt/README.md b/third_party/libassimp/tnt/README.md index e14adb70e4..5a0edf0b28 100644 --- a/third_party/libassimp/tnt/README.md +++ b/third_party/libassimp/tnt/README.md @@ -25,11 +25,4 @@ Other Changes (1) -In glTF2Importer.cpp, change from: - ai_anim->mNumChannels = r.skins[0].jointNames.size(); -to: - ai_anim->mNumChannels = r.skins.Size() > 0 ? r.skins[0].jointNames.size() : 0; - -(2) - -Negate the bitangent in CalcTangentsProcess.cpp +Negate the bitangent in CalcTangentsProcess.cpp (see Filament commit 84eb954).